import { axiosInstance } from "./axios";

export interface PendingPartner {
  id: string;
  email: string;
  createdAt: string;
  assignedNdaId?: string | null;
  assignedMsaId?: string | null;
  acceptances: Array<{
    id: string;
    signatureHash: string | null;
    documentUrl: string | null;
    signatureBase64: string | null;
    ipAddress: string;
    acceptedAt: string;
    document: {
      id: string;
      type: string;
      version: string;
      content: string;
    };
  }>;
}

export interface LegalDocument {
  id: string;
  type: 'NDA' | 'MSA';
  content: string;
  pdfUrl?: string | null;
  version: string;
  skipped?: boolean;
}

export interface LegalAcceptance {
  id: string;
  signatureHash: string | null;
  documentUrl: string | null;
  signatureBase64: string | null;
  ipAddress: string;
  acceptedAt: string;
  document: {
    id: string;
    type: 'NDA' | 'MSA';
    version: string;
    content: string;
    pdfUrl?: string | null;
  };
}

export const LEGAL_API_ROUTES = {
  pending: "/legal/pending",
  approve: (partnerId: string) => `/legal/approve/${partnerId}`,
  activeDoc: (type: 'NDA' | 'MSA') => `/legal/documents/active/${type}`,
  myAcceptances: "/legal/my-acceptances",
  upload: "/legal/upload",
  sign: "/legal/sign",
};

export const getPendingPartners = async (): Promise<PendingPartner[]> => {
  const response = await axiosInstance.get<PendingPartner[]>(LEGAL_API_ROUTES.pending);
  return response.data;
};

export const approvePartnerAccess = async (partnerId: string): Promise<void> => {
  await axiosInstance.post<void>(LEGAL_API_ROUTES.approve(partnerId));
};

export const getLegalDocuments = async (): Promise<LegalDocument[]> => {
  const response = await axiosInstance.get<LegalDocument[]>('/legal/documents');
  return response.data;
};

export const getActiveLegalDocument = async (type: 'NDA' | 'MSA'): Promise<LegalDocument> => {
  const response = await axiosInstance.get<LegalDocument>(LEGAL_API_ROUTES.activeDoc(type));
  return response.data;
};

export const getMyAcceptances = async (): Promise<LegalAcceptance[]> => {
  const response = await axiosInstance.get<LegalAcceptance[]>(LEGAL_API_ROUTES.myAcceptances);
  return response.data;
};

export const uploadSignedLegalDocument = async (formData: FormData): Promise<{ url: string }> => {
  const response = await axiosInstance.post<{ url: string }>(LEGAL_API_ROUTES.upload, formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
  return response.data;
};

export const signLegalDocument = async (payload: {
  documentType: 'NDA' | 'MSA';
  signatureBase64: string | null;
  documentUrl: string | null;
}): Promise<void> => {
  await axiosInstance.post(LEGAL_API_ROUTES.sign, payload);
};
