import { axiosInstance } from "./axios";
import type { AuthResponse, LoginParams } from "../types/auth";

export const AUTH_API_ROUTES = {
  login: "/auth/login",
  refresh: "/auth/refresh",
  logout: "/auth/logout",
  partners: "/auth/partners",
  invite: "/auth/invite",
};

export interface Partner {
  id: string;
  email: string;
  onboardingStatus: string;
  mfaEnabled: boolean;
  createdAt: string;
  partnerGroup?: string | null;
  assignedNdaId?: string | null;
  assignedMsaId?: string | null;
  assignedNda?: { id: string; version: string } | null;
  assignedMsa?: { id: string; version: string } | null;
  sharedAssets?: Array<{ assetId: string }>;
  inviteToken?: string | null;
  showEcosystemTab?: boolean;
}

export interface InviteParams {
  email: string;
  partnerGroup?: string | null;
  assignedNdaId?: string | null;
  assignedMsaId?: string | null;
  sharedAssetIds?: string[];
  mfaEnabled?: boolean;
  showEcosystemTab?: boolean;
}

export interface UpdatePartnerParams {
  partnerGroup?: string | null;
  assignedNdaId?: string | null;
  assignedMsaId?: string | null;
  sharedAssetIds?: string[];
  mfaEnabled?: boolean;
  showEcosystemTab?: boolean;
}

export interface InviteResponse {
  token: string;
  emailSent?: boolean;
  emailError?: string;
}

export const loginUser = async (params: LoginParams): Promise<AuthResponse> => {
  const response = await axiosInstance.post<AuthResponse>(
    AUTH_API_ROUTES.login,
    params,
  );
  return response.data;
};

export const refreshAuthToken = async (): Promise<AuthResponse> => {
  const response = await axiosInstance.post<AuthResponse>(
    AUTH_API_ROUTES.refresh
  );
  return response.data;
};

export const getPartners = async (): Promise<Partner[]> => {
  const response = await axiosInstance.get<Partner[]>(
    AUTH_API_ROUTES.partners
  );
  return response.data;
};

export const invitePartner = async (params: InviteParams): Promise<InviteResponse> => {
  const response = await axiosInstance.post<InviteResponse>(
    AUTH_API_ROUTES.invite,
    params
  );
  return response.data;
};

export const updatePartner = async (partnerId: string, params: UpdatePartnerParams): Promise<Partner> => {
  const response = await axiosInstance.put<Partner>(
    `/auth/partners/${partnerId}`,
    params
  );
  return response.data;
};

export interface UpdateProfileParams {
  password?: string;
  companyName?: string;
  website?: string;
  sector?: string;
  companySize?: string;
  defaultTheme?: string;
}

export const updateProfile = async (params: UpdateProfileParams): Promise<any> => {
  const response = await axiosInstance.put<any>(
    '/auth/profile',
    params
  );
  return response.data;
};

export const resendInvitePartner = async (partnerId: string): Promise<{ success: boolean }> => {
  const response = await axiosInstance.post<{ success: boolean }>(
    `/auth/partners/${partnerId}/resend-invite`
  );
  return response.data;
};
