"use server";

import { createClient } from "@/utils/supabase/server";
import { encodedRedirect } from "@/utils/utils";
import { redirect } from "next/navigation";
import { checkSession } from "./session";

export const signInAction = async (formData: FormData) => {
  const supabase = await createClient();
  const email = formData.get("email") as string;
  const encodeEmail = encodeURIComponent(email);

  try {
    // First, check for existing session
    const { session, error: sessionError } = await checkSession();

    // If there's an active session and the email matches
    if (session && session.user.email === email) {
      return {
        success: true,
        message: "Already logged in",
        redirectTo: "/protected/dashboard", // or wherever you want to redirect logged in users
      };
    }

    // If no active session or different email, proceed with OTP
    const { data, error } = await supabase.auth.signInWithOtp({
      email,
      options: {
        shouldCreateUser: false,
      },
    });

    if (error) {
      return {
        success: false,
        error: error.message,
        redirectTo: `/verify-otp?email=${encodeEmail}`,
      };
    }

    return {
      success: true,
      message: "OTP has been sent to your email",
      redirectTo: `/verify-otp?email=${encodeEmail}`,
    };
  } catch (error) {
    return {
      success: false,
      error: "An unexpected error occurred",
      redirectTo: "/sign-in",
    };
  }
};
