"use server";

import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { registerSchema } from "./schemas";
import { authService } from "@/server/services/auth.service";
import { userRepo } from "@/server/repositories/user.repo";

export async function registerAction(formData: FormData) {
  const raw = {
    name: formData.get("name") as string,
    email: formData.get("email") as string,
    password: formData.get("password") as string,
    confirmPassword: formData.get("confirmPassword") as string,
    acceptedTermsAndPrivacy: formData.get("acceptedTermsAndPrivacy") === "on",
  };

  const result = registerSchema.safeParse(raw);
  if (!result.success) {
    return { error: result.error.issues[0].message };
  }

  try {
    await authService.register({
      name: result.data.name,
      email: result.data.email,
      password: result.data.password,
      acceptedTermsAndPrivacy: result.data.acceptedTermsAndPrivacy,
    });
    return { success: true };
  } catch (err) {
    return { error: (err as Error).message };
  }
}

export async function acceptTermsAction(input: { accepted: boolean }) {
  if (input?.accepted !== true) {
    return {
      error:
        "Kamu harus mencentang persetujuan Syarat & Ketentuan dan Kebijakan Privasi",
    };
  }
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return { error: "Kamu harus login terlebih dahulu" };
  }
  try {
    await userRepo.markAcceptedTerms(session.user.id);
    return { success: true };
  } catch (err) {
    return { error: (err as Error).message };
  }
}
