import client from './client';
import axios from 'axios';
import type { ConstitutionalChangeAction } from '@/lib/offboarding-actions';

const PUBLIC_API_BASE_URL = (import.meta as any).env?.VITE_API_URL || '/api';

export const API = {
    // Auth routes
    login: (data: any) => client.post('/auth/login', data),
    logout: () => client.post('/auth/logout'),
    getCurrentUser: () => client.get('/auth/me'),

    // Master module routes
    getRoles: () => client.get('/admin/roles'),
    createRole: (data: any) => client.post('/admin/roles', data),
    getPermissions: () => client.get('/admin/permissions'),
    updateRole: (id: string, data: any) => client.put(`/admin/roles/${id}`, data),

    getZones: () => client.get('/master/zones'),
    createZone: (data: any) => client.post('/master/zones', data),
    updateZone: (id: string, data: any) => client.put(`/master/zones/${id}`, data),
    createRegion: (data: any) => client.post('/master/regions', data),
    updateRegion: (id: string, data: any) => client.put(`/master/regions/${id}`, data),
    getRegions: () => client.get('/master/regions'),
    getOutlets: () => client.get('/outlets'),
    getOutletByCode: (code: string) => client.get(`/master/outlets/code/${code}`),
    getStates: (params?: any) => client.get('/master/states', typeof params === 'string' ? { zoneId: params } : params),
    getDistricts: (params?: any) => client.get('/master/districts', typeof params === 'string' ? { stateId: params } : params),
    getAreas: (params?: any) => client.get('/master/areas', params),
    updateArea: (id: string, data: any) => client.put(`/master/areas/${id}`, data),
    createArea: (data: any) => client.post('/master/areas', data),
    getAreaManagers: () => client.get('/master/area-managers'),
    getASMs: () => client.get('/master/asms'),
    getZonalManagers: () => client.get('/master/zonal-managers'),
    saveZonalManager: (data: any) => client.post('/master/zonal-managers', data),
    getDDLeads: () => client.get('/master/dd-leads'),
    saveDDLead: (data: any) => client.post('/master/dd-leads', data),
    getManagersByRole: (params: any) => client.get('/master/managers', params),


    // Onboarding
    submitApplication: (data: any) => client.post('/onboarding/apply', data),
    exportApplicationResponses: (params: { applicationIds: string }) => client.get('/onboarding/applications/export-responses', params),
    getApplications: (params?: any) => client.get('/onboarding/applications', params),
    shortlistApplications: (data: any) => client.post('/onboarding/applications/shortlist', data),
    sendBulkReminders: (data: { applicationIds: string[] }) => client.post('/onboarding/applications/reminders', data),
    getApplicationById: (id: string) => client.get(`/onboarding/applications/${id}`),
    updateApplication: (id: string, data: any) => client.put(`/onboarding/applications/${id}`, data),
    getLatestQuestionnaire: () => client.get('/questionnaire/latest'),
    createQuestionnaireVersion: (data: any) => client.post('/questionnaire/version', data),
    submitQuestionnaireResponse: (data: any) => client.post('/questionnaire/response', data),
    getAllQuestionnaires: () => client.get('/onboarding/questionnaires'),
    getQuestionnaireById: (id: string) => client.get(`/onboarding/questionnaires/${id}`),
    assignArchitectureTeam: (applicationId: string, assignedTo: string) => client.post(`/onboarding/applications/${applicationId}/assign-architecture`, { assignedTo }),
    updateArchitectureStatus: (applicationId: string, status: string, remarks?: string) => client.post(`/onboarding/applications/${applicationId}/architecture-status`, { status, remarks }),
    generateDealerCodes: (applicationId: string) => client.post(`/onboarding/applications/${applicationId}/generate-codes`),
    updateApplicationStatus: (id: string, data: any) => client.put(`/onboarding/applications/${id}/status`, data),
    convertToOpportunity: (id: string, data?: any) => client.post(`/onboarding/applications/${id}/convert-to-opportunity`, data),
    bulkConvertToOpportunity: (data: any) => client.post('/onboarding/applications/bulk-convert-to-opportunity', data),
    retriggerEvaluators: (id: string) => client.post(`/onboarding/applications/${id}/retrigger-evaluators`),
    getSecurityDeposit: (applicationId: string) => client.get(`/loa/security-deposit/${applicationId}`),
    updateSecurityDeposit: (data: any) => client.post('/loa/security-deposit', data),

    // Documents
    uploadDocument: (id: string, data: any) => client.post(`/onboarding/applications/${id}/documents`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    getDocuments: (id: string) => client.get(`/onboarding/applications/${id}/documents`),
    getDocumentConfigMetadata: () => client.get('/onboarding/document-configs/metadata'),
    getDocumentConfigs: (params?: any) => client.get('/onboarding/document-configs', params),
    createDocumentConfig: (data: any) => client.post('/onboarding/document-configs', data),
    updateDocumentConfig: (id: string, data: any) => client.put(`/onboarding/document-configs/${id}`, data),
    deleteDocumentConfig: (id: string) => client.delete(`/onboarding/document-configs/${id}`),

    // Public Questionnaire
    getPublicQuestionnaire: (appId: string) => axios.get(`${PUBLIC_API_BASE_URL}/questionnaire/public/${appId}`), // Direct axios to bypass interceptors if client has auth
    submitPublicResponse: (data: any) => axios.post(`${PUBLIC_API_BASE_URL}/questionnaire/public/submit`, data),

    // Assessment & Interviews
    getAiSummary: (appId: string) => client.get(`/assessment/ai-summary/${appId}`),
    scheduleInterview: (data: any) => client.post('/assessment/interviews', data),
    updateInterview: (id: string, data: any) => client.put(`/assessment/interviews/${id}`, data),
    submitEvaluation: (id: string, data: any) => client.post(`/assessment/interviews/${id}/evaluation`, data),
    submitKTMatrix: (data: any) => client.post('/assessment/kt-matrix', data),
    submitLevel2Feedback: (data: any) => client.post('/assessment/level2-feedback', data),
    getInterviews: (applicationId: string) => client.get(`/assessment/interviews/${applicationId}`),
    updateRecommendation: (data: any) => client.post('/assessment/recommendation', data),
    updateInterviewDecision: (data: any) => client.post('/assessment/decision', data),
    submitStageDecision: (data: any) => client.post('/assessment/stage-decision', data),
    getInterviewApprovalStatus: (interviewId: string) => client.get(`/assessment/interviews/${interviewId}/approval-status`),
    getApprovalPolicies: () => client.get('/assessment/approval-policies'),
    upsertApprovalPolicy: (stageCode: string, data: any) => client.put(`/assessment/approval-policies/${stageCode}`, data),

    // Collaboration & Participants
    getWorknotes: (requestId: string, requestType: string) => client.get('/collaboration/worknotes', { requestId, requestType }),
    addWorknote: (data: any) => client.post('/collaboration/worknotes', data),
    addParticipant: (data: any) => client.post('/collaboration/participants', data),
    removeParticipant: (id: string) => client.delete(`/collaboration/participants/${id}`),

    // User management routes
    getUsers: (params?: any) => client.get('/admin/users', params),
    createUser: (data: any) => client.post('/admin/users', data),
    updateUser: (id: string, data: any) => client.put(`/admin/users/${id}`, data),
    updateUserStatus: (id: string, data: any) => client.patch(`/admin/users/${id}/status`, data),
    deleteUser: (id: string) => client.delete(`/admin/users/${id}`),

    // Dealer & Outlets
    getDealers: (params?: { onboarded?: string; activeOnly?: string }) => client.get('/dealer', params),
    createDealer: (data: any) => client.post('/dealer', data),
    getDealerById: (id: string) => client.get(`/dealer/${id}`),
    updateDealer: (id: string, data: any) => client.put(`/dealer/${id}`, data),
    getDealerDashboard: () => client.get('/dealer/dashboard'),
    getDealerBankDetails: (dealerId: string) => client.get(`/dealer/${dealerId}/bank-details`),
    saveBankDetail: (dealerId: string, data: any) => client.post(`/dealer/${dealerId}/bank-details`, data),
    deleteBankDetail: (id: string) => client.delete(`/dealer/bank-details/${id}`),

    // Email Templates
    getEmailTemplates: () => client.get('/admin/email-templates'),
    getEmailTemplate: (id: string) => client.get(`/admin/email-templates/${id}`),
    createEmailTemplate: (data: any) => client.post('/admin/email-templates', data),
    updateEmailTemplate: (id: string, data: any) => client.put(`/admin/email-templates/${id}`, data),
    deleteEmailTemplate: (id: string) => client.delete(`/admin/email-templates/${id}`),
    previewEmailTemplate: (data: any) => client.post('/admin/email-templates/preview', data),

    // Audit Trail
    getAuditLogs: (entityType: string, entityId: string, page: number = 1, limit: number = 50) =>
        client.get('/audit/logs', { entityType, entityId, page, limit }),
    getAuditSummary: (entityType: string, entityId: string) =>
        client.get('/audit/summary', { entityType, entityId }),

    // Prospective Login
    sendOtp: (phone: string) => client.post('/prospective-login/send-otp', { phone }),
    verifyOtp: (phone: string, otp: string) => client.post('/prospective-login/verify-otp', { phone, otp }),
    
    // Resignation
    getResignationById: (id: string) => client.get(`/resignation/${id}`),
    uploadResignationDocument: (id: string, data: any) => client.post(`/resignation/${id}/documents`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    updateClearance: (id: string, data: any) => client.put(`/resignation/${id}/clearance`, data, {
        headers: data instanceof FormData ? { 'Content-Type': 'multipart/form-data' } : {}
    }),
    updateResignationStatus: (id: string, data: any) => client.post(`/resignation/${id}/status`, data),

    // Termination
    getTerminationById: (id: string) => client.get(`/termination/${id}`),
    uploadTerminationDocument: (id: string, data: any) => client.post(`/termination/${id}/documents`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    updateTerminationStatus: (id: string, data: any) => client.post(`/termination/${id}/status`, data),
    issueSCN: (id: string, data: any) => client.post(`/termination/${id}/scn`, data),
    uploadSCNResponse: (id: string, data: any) => client.post(`/termination/${id}/scn-response`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    finalizeTermination: (id: string, data: any) => client.post(`/termination/${id}/finalize`, data),

    // Lifecycle Modules (Self-Service)
    getResignations: (params?: any) => client.get('/resignation', params),
    createResignation: (data: any) => client.post('/resignation', data),
    approveResignation: (id: string, data?: any) => client.post(`/resignation/${id}/approve`, data),
    rejectResignation: (id: string, data: any) => client.post(`/resignation/${id}/reject`, data),
    withdrawResignation: (id: string, reason: string) => client.post(`/resignation/${id}/withdraw`, { reason }),

    getTerminations: (params?: any) => client.get('/termination', params),
    createTermination: (data: any) => client.post('/termination', data),
    updateTermination: (id: string, data: any) => client.post(`/termination/${id}/status`, data),

    getOnboardingPayments: () => client.get('/settlement/onboarding'),
    updatePayment: (id: string, data: any) => client.put(`/settlement/payments/${id}`, data),
    getFnFSettlements: () => client.get('/settlement/fnf'),
    getFnFSettlementById: (id: string) => client.get(`/settlement/fnf/${id}`),
    calculateFnF: (id: string) => client.post(`/settlement/fnf/${id}/calculate`),
    updateFnF: (id: string, data: any) => client.put(`/settlement/fnf/${id}`, data),
    uploadFnFDocument: (id: string, data: any) => client.post(`/settlement/fnf/${id}/documents`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    getSettlementDepartments: () => client.get('/settlement/departments'),

    // Line items
    addLineItem: (fnfId: string, data: any) => client.post(`/settlement/fnf/${fnfId}/line-items`, data),
    updateFnFClearance: (fnfId: string, clearanceId: string, data: any) => client.put(`/settlement/fnf/${fnfId}/clearances/${clearanceId}`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    updateLineItem: (itemId: string, data: any) => client.put(`/settlement/fnf/line-items/${itemId}`, data),
    deleteLineItem: (itemId: string) => client.delete(`/settlement/fnf/line-items/${itemId}`),

    getRelocationRequests: (params?: any) => client.get('/relocation', params),
    getRelocationRequestById: (id: string) => client.get(`/relocation/${id}`),
    createRelocationRequest: (data: any) => client.post('/relocation', data),
    updateRelocationRequest: (id: string, action: string, data?: any) => client.post(`/relocation/${id}/action`, { action, ...data }),
    uploadRelocationDocument: (id: string, data: any) => client.post(`/relocation/${id}/documents`, data, {
        headers: { 'Content-Type': 'multipart/form-data' }
    }),
    verifyRelocationDocument: (id: string, documentId: string) => client.post(`/relocation/${id}/documents/${documentId}/verify`),
    rejectRelocationDocument: (id: string, documentId: string, data?: any) =>
        client.post(`/relocation/${id}/documents/${documentId}/reject`, data || {}),

    getConstitutionalChanges: (params?: any) => client.get('/constitutional-change', params),
    getConstitutionalChangeMeta: () => client.get('/constitutional-change/meta'),
    getConstitutionalChangeById: (id: string) => client.get(`/constitutional-change/${id}`),
    createConstitutionalChange: (data: any) => client.post('/constitutional-change', data),
    /**
     * POST `/constitutional-change/:id/action`
     * Body: `{ action, comments? }` — `action` must be `approve` | `sendBack` | `reject` | `revoke` (see `OFFBOARDING_ACTIONS` in `@/lib/offboarding-actions`).
     * Backend also accepts `remarks` as an alias for `comments`.
     */
    updateConstitutionalChange: (id: string, action: ConstitutionalChangeAction, data?: { comments?: string; remarks?: string }) =>
        client.post(`/constitutional-change/${id}/action`, { action, ...data }),
    uploadConstitutionalDocuments: (id: string, documents: any[]) => client.post(`/constitutional-change/${id}/documents`, { documents }),

    // SLA
    getSlaConfigs: () => client.get('/master/sla-configs'),
    saveSlaConfig: (data: any) => client.post('/master/sla-configs', data),
    initializeDefaultSlas: () => client.post('/master/sla-configs/initialize'),

    // Interview Configs
    getInterviewConfigs: (params?: any) => client.get('/master/interview-configs', params),
    getInterviewConfigById: (id: string) => client.get(`/master/interview-configs/${id}`),
    getInterviewConfigByType: (configType: string) => client.get(`/master/interview-configs/active/${configType}`),
    createInterviewConfig: (data: any) => client.post('/master/interview-configs', data),
    updateInterviewConfig: (id: string, data: any) => client.put(`/master/interview-configs/${id}`, data),
    deleteInterviewConfig: (id: string) => client.delete(`/master/interview-configs/${id}`),
    initializeDefaultInterviewConfigs: () => client.post('/master/interview-configs/initialize'),

    // System Configs
    getSystemConfigs: (params?: any) => client.get('/master/system-configs', params),
    saveSystemConfig: (data: any) => client.post('/master/system-configs', data),
    getDealerAsmMappings: () => client.get('/master/dealer-asm-mappings'),
    saveDealerAsmMapping: (data: { dealerId: string; asmUserId?: string | null }) => client.post('/master/dealer-asm-mappings', data),
    
    // EOR Checklist
    getEorChecklistForApplication: (applicationId: string) => client.get(`/eor/application/${applicationId}`),
    getEorChecklistForRelocation: (relocationId: string) => client.get(`/eor/relocation/${relocationId}`),
    updateEorChecklistItem: (checklistId: string, data: any) => client.post(`/eor/item/${checklistId}`, data),
    submitEorAudit: (checklistId: string, data: any) => client.post(`/eor/audit/${checklistId}`, data),
    
    // FDD module additional routes
    submitFddReport: (data: any) => client.post('/fdd/report', data),
    getFddAssignment: (applicationId: string) => client.get(`/fdd/${applicationId}`),
    assignFddAgency: (data: any) => client.post('/fdd/assign', data),
    flagNonResponsive: (data: any) => client.post('/flag', data),

    // System Audit Logs (segregated `system_audit_logs` table — Super Admin only)
    getSystemAuditLogs: (params?: {
        module?: string;
        entityType?: string;
        entityId?: string;
        action?: string;
        userId?: string;
        search?: string;
        dateFrom?: string;
        dateTo?: string;
        page?: number;
        limit?: number;
    }) => client.get('/audit/system-logs', params),
    getSystemAuditSummary: () => client.get('/audit/system-summary'),
};

export default API;
