"use server";

import { headers } from "next/headers";
import { z } from "zod";

import { auth } from "@/lib/auth";

const RequestSchema = z.object({ email: z.email() });
const VerifySchema = z.object({ email: z.email(), otp: z.string().min(4).max(8) });

export async function requestEmailVerificationOTP(input: { email: string }) {
  const { email } = RequestSchema.parse(input);
  await auth.api.sendVerificationOTP({
    headers: await headers(),
    body: { email, type: "email-verification" },
  });
}

export async function verifyEmailWithOTP(input: { email: string; otp: string }) {
  const parsed = VerifySchema.parse(input);
  return await auth.api.verifyEmailOTP({
    headers: await headers(),
    body: { email: parsed.email, otp: parsed.otp },
  });
}

const ForgotSchema = z.object({ email: z.email() });
const ResetSchema = z.object({
  email: z.email(),
  otp: z.string().min(4).max(8),
  newPassword: z.string().min(8).max(128),
});

export async function requestPasswordResetOTP(input: { email: string }) {
  const { email } = ForgotSchema.parse(input);
  await auth.api.sendVerificationOTP({
    headers: await headers(),
    body: { email, type: "forget-password" },
  });
}

export async function resetPasswordWithOTP(input: {
  email: string;
  otp: string;
  newPassword: string;
}) {
  const parsed = ResetSchema.parse(input);
  return await auth.api.resetPasswordEmailOTP({
    headers: await headers(),
    body: { email: parsed.email, otp: parsed.otp, password: parsed.newPassword },
  });
}
