import { URL_CONSTANTS } from "@/constants/URLS";
import type {
    AuthUser,
    GenerateVerificationCodePayload,
    LoginPayload,
    LoginResponse,
    OtpPayload,
    OtpResponse,
    SetPasswordPayload,
    SignupPayload,
    SignupResponse,
} from "@/types/auth";
import { client } from "@/utils/api";
import { ApiResponse } from "@edr/types";

export const authService = {
  login: async (body: LoginPayload) => {
    const res = await client.post<LoginResponse>(
      URL_CONSTANTS.AUTH.LOGIN,
      body,
    );
    return res.data;
  },

  createUser: async (body: SignupPayload) => {
    const res = await client.post<SignupResponse & ApiResponse<void>> (
      URL_CONSTANTS.USERS.SIGN_UP,
      body,
    );
    return res.data;
  },

  getMyInfo: async () => {
    const res = await client.get<AuthUser>(
      URL_CONSTANTS.USERS.ME,
    );
    return res.data;
  },

  generateVerificationCode: async (body: GenerateVerificationCodePayload) => {
    const res = await client.patch<ApiResponse<string>>(
      URL_CONSTANTS.USERS.GENERATE_VERIFICATION_CODE,
      body,
    );
    return res.data.data;
  },

  setPassword: async (body: SetPasswordPayload) => {
    const res = await client.patch<ApiResponse<void>>(
      URL_CONSTANTS.USERS.SET_PASSWORD,
      body,
    );
    return res.data.data;
  },

  sendOTP: async (body: OtpPayload) => {
    const res = await client.post<ApiResponse<OtpResponse>>(
      URL_CONSTANTS.OTP.SEND,
      body,
    );
    return res.data.data;
  },

  verifyOTP: async (body: OtpPayload) => {
    const res = await client.post<ApiResponse<OtpResponse>>(
      URL_CONSTANTS.OTP.VERIFY,
      body,
    );
    return res.data.data;
  },

  refreshToken: async () => {
    const refreshTokenCookie = document.cookie
      .split("; ")
      .find((row) => row.startsWith("refresh-token="))
      ?.split("=")[1];
    const res = await client.post<ApiResponse<LoginResponse>>(
      URL_CONSTANTS.AUTH.REFRESH_TOKEN,
      { refreshToken: refreshTokenCookie },
    );
    return res.data.data;
  },

  logout: async () => {
    const res = await client.patch<ApiResponse<void>>(
      URL_CONSTANTS.AUTH.LOGOUT,
    );
    return res.data.data;
  },
};
