import { API_URL } from "../constants";
import httpStatusCodes from "../constants/http-status-codes";
import type { Sesion } from "../models/Sesion.model";
import type { DefaultResponse } from "../types/responses";
import { HttpService } from "./httpService";
import { authStore } from "../stores";

export interface IAuthService {
  login: <T>(correo: string, clave: string) => Promise<DefaultResponse<T>>;
  logout: () => any;
  usuario?: Sesion | null;
  isActive?: boolean;
}

export class AuthService extends HttpService implements IAuthService {

  constructor(api_url: string) {
    super(api_url);
  }

  DEFAULT_HEADERS = () => {
    let headers: Record<string, string> = {
      "Content-Type": "application/json",
    };
    if (this.isActive) {
      headers.Authorization = `Bearer ${this.usuario?.token}`;
    }
    return headers;
  };

  FILE_HEADERS = () => {
    let headers: Record<string, string> = {
      "Content-Type": "application/json",
    };
    if (this.isActive) {
      headers.Authorization = `Bearer ${this.usuario?.token}`;
    }
    return headers;
  };

  async login<Sesion>(
    correo?: string,
    clave?: string
  ): Promise<DefaultResponse<Sesion>> {
    const body = {
      correo,
      clave,
    };

    const res = await this.post("aspirante/iniciar-sesion.json", body);

    if (res.status === httpStatusCodes.OK) {
      authStore.set(res.detalle as Partial<Sesion>);
      window.location.href = "/";
    }

    throw new Error("Login");
  }

  logout() {
    authStore.set(undefined);
    window.location.href = "/";
  }

  get isActive(): boolean {
    let active = false;
    if (authStore.get()) {
      active = true;
    }
    return active;
  }

  get usuario(): Sesion | undefined {
    if (typeof window === "undefined") {
      return;
    }
    return authStore.get();
  }
}

export const auth = new AuthService(API_URL);
