// src/repositories/auth.repository.ts
import { createClient } from "@/utils/supabase/server";
import { SignInFormData } from "../models/auth/sign-in.model";
import { VerifyOtpFormData } from "../models/auth/verify-otp.model";

export class AuthRepository {
  async signIn({ email }: SignInFormData) {
    const supabase = await createClient();
    const { data, error } = await supabase.auth.signInWithOtp({
      email,
      options: {
        shouldCreateUser: false,
      },
    });
    
    if (error) {
      throw new Error(error.message);
    }
    
    return {
      data,
      redirectTo: `/verify-otp?email=${encodeURIComponent(email)}`
    };
  }
  
  async signOut() {
    const supabase = await createClient();
    const { error } = await supabase.auth.signOut();
    
    if (error) {
      throw new Error(error.message);
    }
    
    return {
      success: true,
      redirectTo: "/"
    };
  }
  
  async getUser() {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    return user;
  }
  
  async verifyOtp({ email, token }: VerifyOtpFormData) {
    const supabase = await createClient();
    const { data, error } = await supabase.auth.verifyOtp({
      email,
      token,
      type: "email",
    });
      
    if (error) {
      throw new Error(error.message);
    }
    
    return {
      data,
      redirectTo: "/protected/dashboard"
    };
  }
}

export const authRepository = new AuthRepository();