"use server";
import axios from "axios";
import { ZodFormattedError } from "zod";
import { registerSchema, loginSchema, RegisterSchemaType, LoginSchemaType } from "../validations/authSchema";

// Define common response type
interface AuthResponse {
  success: boolean;
  message?: string;
  errors?: ZodFormattedError<RegisterSchemaType | LoginSchemaType>;
  authData?: any; // You can replace `any` with a stricter type based on your backend response
}

// Register User
export async function registerUser(data: RegisterSchemaType): Promise<AuthResponse> {
  // const result = registerSchema.safeParse(data);
  // if (!result.success) {
  //   return { success: false, errors: result.error.format() };
  // }

  try {
    // Normally you'd call an API here
    return { success: true, message: "Registration successful!" };
  } catch (error) {
    return { success: false, message: "Registration failed" };
  }
}

// Login User
export async function loginUser(data: LoginSchemaType): Promise<AuthResponse> {
  // const result = loginSchema(t).safeParse(data);
  // if (!result.success) {
  //   return { success: false, errors: result.error.format() };
  // }

  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/token`;
    const response = await axios.post(
      url,
      data,
      { headers: { "Content-Type": "application/json" } }
    );
    return {
      success: true,
      message: "Login successful!",
      authData: response?.data,
    };
  } catch (error:any) {
    return {
      success: false,
      message: error.response.data.message ?? "Login failed",
      
    };
  }
}
