import { apiClient } from './apiClient'
import { Company } from './adminService'

export interface CompanyDocument {
    id: string
    company_id: string
    type: string
    status: 'PENDING' | 'APPROVED' | 'REJECTED'
    url: string
    created_at: string
    rejection_reason?: string
}

export interface LedgerEntry {
    id: string
    company_id: string
    amount: number
    balance_after: number
    description: string
    type: 'CREDIT' | 'DEBIT'
    reference_id: string
    created_at: string
}

export interface Withdrawal {
    id: string
    company_id: string
    amount: number
    status: 'PENDING' | 'APPROVED' | 'REJECTED'
    requested_at: string
    processed_at?: string
}

export const financialService = {
    getMyCompany: async () => {
        const result = await apiClient.get<Company>('/v1/companies/me')
        return result
    },

    uploadDocument: async (file: File, type: string) => {
        const formData = new FormData()
        formData.append('document', file)
        formData.append('type', type)
        // apiClient wrapper should handle Content-Type header removal for FormData
        const result = await apiClient.post<CompanyDocument>('/v1/companies/documents', formData)
        return result
    },

    listDocuments: async () => {
        const result = await apiClient.get<{ documents: CompanyDocument[] }>('/v1/companies/documents')
        return result.documents
    },

    getBalance: async () => {
        const result = await apiClient.get<{ balance: number }>('/v1/finance/balance')
        return result.balance
    },

    getLedger: async (page = 1, limit = 20) => {
        const result = await apiClient.get<{ entries: LedgerEntry[], total: number }>(`/v1/finance/ledger?page=${page}&limit=${limit}`)
        return result
    },

    requestWithdrawal: async (amount: number) => {
        const result = await apiClient.post<Withdrawal>('/v1/finance/withdrawals', { amount })
        return result
    }
}
