// src/app/(auth-pages)/actions.ts
"use server";


import { SignInFormData } from "@/src/models/auth/sign-in.model";
import { VerifyOtpFormData } from "@/src/models/auth/verify-otp.model";
import { authRepository } from "@/src/repositories/authentication.repository";
import { redirect } from "next/navigation";

export async function signIn(
  data: SignInFormData
): Promise<{ success: boolean; message: string; redirectTo?: string }> {
  try {
    const result = await authRepository.signIn(data);
    return {
      success: true,
      message: "Check your email for the login link!",
      redirectTo: result.redirectTo
    };
  } catch (error) {
    console.error("Authentication error:", error);
    return {
      success: false,
      message:
        error instanceof Error
          ? error.message
          : "Authentication failed. Please try again.",
    };
  }
}

export async function verifyOtp(
  data: VerifyOtpFormData
): Promise<{ success: boolean; message: string; redirectTo?: string }> {
  try {
    const result = await authRepository.verifyOtp(data);
    return {
      success: true,
      message: "Successfully authenticated!",
      redirectTo: result.redirectTo
    };
  } catch (error) {
    console.error("OTP verification error:", error);
    return {
      success: false,
      message:
        error instanceof Error
          ? error.message
          : "OTP verification failed. Please try again.",
    };
  }
}

export async function signOut() {
  try {
    const result = await authRepository.signOut();
    return {
      success: true,
      redirectTo: result.redirectTo
    };
  } catch (error) {
    console.error("Sign out error:", error);
    return {
      success: false,
      message:
        error instanceof Error
          ? error.message
          : "Sign out failed. Please try again.",
    };
  }
}
