import type { User } from "./types";

const AUTH_KEY = "job-portal-auth";
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8521/api/v1";

interface LoginResponse {
  token: string;
  user: {
    id: string;
    name: string;
    email: string;
    roles: string[];
    status: string;
    created_at: string;
  };
}

export async function login(
  email: string,
  password: string,
  role?: "candidate" | "admin" | "company" // Deprecated argument, kept for signature compatibility if needed, but ignored
): Promise<User | null> {
  try {
    const res = await fetch(`${API_URL}/auth/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ email, password }),
    });

    if (!res.ok) {
      if (res.status === 401) {
        throw new Error("Credenciais inválidas");
      }
      throw new Error("Erro no servidor");
    }

    const data: LoginResponse = await res.json();

    // Map backend response to frontend User type
    // Note: The backend returns roles as an array of strings. The frontend expects a single 'role' or we need to adapt.
    // For now we map the first role or main role to the 'role' field.
    let userRole: "candidate" | "admin" | "company" = "candidate";
    if (data.user.roles.includes("superadmin") || data.user.roles.includes("admin")) {
      userRole = "admin";
    } else if (data.user.roles.includes("companyAdmin") || data.user.roles.includes("recruiter")) {
      userRole = "company";
    }

    const user: User = {
      id: data.user.id,
      name: data.user.name,
      email: data.user.email,
      role: userRole,
      roles: data.user.roles, // Extend User type if needed, or just keep it here
      profileComplete: 80, // Mocked for now
    };

    if (typeof window !== "undefined") {
      localStorage.setItem(AUTH_KEY, JSON.stringify(user));
      localStorage.setItem("auth_token", data.token);
    }

    return user;
  } catch (error) {
    console.error("Login error:", error);
    throw error;
  }
}

export function logout(): void {
  if (typeof window !== "undefined") {
    localStorage.removeItem(AUTH_KEY);
    localStorage.removeItem("auth_token");
  }
}

export function getCurrentUser(): User | null {
  if (typeof window !== "undefined") {
    const stored = localStorage.getItem(AUTH_KEY);
    if (stored) {
      return JSON.parse(stored);
    }
  }
  return null;
}

export function isAuthenticated(): boolean {
  return getCurrentUser() !== null;
}

export function getToken(): string | null {
  if (typeof window !== "undefined") {
    return localStorage.getItem("auth_token");
  }
  return null;
}
