import { api } from './api';
import { PageResponse, PageRequest } from '@/types/backend';
import {
  FiscalYearDTO,
  CreateFiscalYearDTO,
  BudgetLineDTO,
  CreateBudgetLineDTO,
  BudgetExecutionDTO,
  CreateBudgetExecutionDTO,
  BudgetEntryDTO,
  CreateBudgetEntryDTO
} from '@/types/budget';

const FISCAL_YEARS_URL = '/budget/fiscal-years';
const BUDGET_LINES_URL = '/budget/lines';
const BUDGET_EXECUTION_URL = '/budget/execution';
const BUDGET_ENTRIES_URL = '/budget/entries';

export const budgetService = {
  // Fiscal Years
  getFiscalYears: async (): Promise<FiscalYearDTO[]> => {
    const response = await api.get<PageResponse<FiscalYearDTO>>(FISCAL_YEARS_URL);
    return response.content;
  },

  getCurrentFiscalYear: async (): Promise<FiscalYearDTO> => {
    return api.get<FiscalYearDTO>(`${FISCAL_YEARS_URL}/current`);
  },

  getFiscalYearById: async (id: string): Promise<FiscalYearDTO> => {
    return api.get<FiscalYearDTO>(`${FISCAL_YEARS_URL}/${id}`);
  },

  createFiscalYear: async (dto: CreateFiscalYearDTO): Promise<FiscalYearDTO> => {
    return api.post<FiscalYearDTO>(FISCAL_YEARS_URL, dto);
  },

  openFiscalYear: async (id: string): Promise<FiscalYearDTO> => {
    return api.post<FiscalYearDTO>(`${FISCAL_YEARS_URL}/${id}/open`, {});
  },

  closeFiscalYear: async (id: string): Promise<FiscalYearDTO> => {
    return api.post<FiscalYearDTO>(`${FISCAL_YEARS_URL}/${id}/close`, {});
  },

  // Budget Lines
  getBudgetLines: async (pageRequest: PageRequest & {
    fiscalYearId?: string;
    ministryId?: string;
    orgUnitId?: string;
    search?: string;
  }): Promise<PageResponse<BudgetLineDTO>> => {
    const {
      page = 0,
      size = 20,
      sortBy,
      sortDirection,
      fiscalYearId,
      ministryId,
      orgUnitId,
      search,
    } = pageRequest;
    const params = new URLSearchParams();
    params.append('page', page.toString());
    params.append('size', size.toString());
    if (sortBy) {
      params.append('sortBy', sortBy);
    }
    if (sortDirection) {
      params.append('sortDirection', sortDirection);
    }
    if (fiscalYearId) {
      params.append('fiscalYearId', fiscalYearId);
    }
    if (ministryId) {
      params.append('ministryId', ministryId);
    }
    if (orgUnitId) {
      params.append('orgUnitId', orgUnitId);
    }
    if (search) {
      params.append('search', search);
    }
    return api.getPage<BudgetLineDTO>(`${BUDGET_LINES_URL}?${params.toString()}`);
  },

  getBudgetLineById: async (id: string): Promise<BudgetLineDTO> => {
    return api.get<BudgetLineDTO>(`${BUDGET_LINES_URL}/${id}`);
  },

  createBudgetLine: async (dto: CreateBudgetLineDTO): Promise<BudgetLineDTO> => {
    return api.post<BudgetLineDTO>(BUDGET_LINES_URL, dto);
  },

  updateBudgetLine: async (id: string, dto: CreateBudgetLineDTO): Promise<BudgetLineDTO> => {
    return api.put<BudgetLineDTO>(`${BUDGET_LINES_URL}/${id}`, dto);
  },

  // Budget Entries
  getBudgetEntries: async (budgetLineId: string, pageRequest: PageRequest): Promise<PageResponse<BudgetEntryDTO>> => {
    const { page = 0, size = 20, sortBy, sortDirection } = pageRequest;
    const params = new URLSearchParams();
    params.append('budgetLineId', budgetLineId);
    params.append('page', page.toString());
    params.append('size', size.toString());
    if (sortBy) params.append('sortBy', sortBy);
    if (sortDirection) params.append('sortDirection', sortDirection);

    return api.getPage<BudgetEntryDTO>(`${BUDGET_ENTRIES_URL}?${params.toString()}`);
  },

  createBudgetEntry: async (dto: CreateBudgetEntryDTO): Promise<BudgetEntryDTO> => {
    return api.post<BudgetEntryDTO>(BUDGET_ENTRIES_URL, dto);
  },

  // Budget Execution
  getBudgetExecutions: async (pageRequest: PageRequest & {
    budgetLineId?: string;
    periodId?: number;
    movementType?: string;
  }): Promise<PageResponse<BudgetExecutionDTO>> => {
    const {
      page = 0,
      size = 20,
      sortBy,
      sortDirection,
      budgetLineId,
      periodId,
      movementType,
    } = pageRequest;
    const params = new URLSearchParams();
    params.append('page', page.toString());
    params.append('size', size.toString());
    if (sortBy) {
      params.append('sortBy', sortBy);
    }
    if (sortDirection) {
      params.append('sortDirection', sortDirection);
    }
    if (budgetLineId) {
      params.append('budgetLineId', budgetLineId);
    }
    if (periodId) {
      params.append('periodId', periodId.toString());
    }
    if (movementType) {
      params.append('movementType', movementType);
    }
    return api.getPage<BudgetExecutionDTO>(`${BUDGET_EXECUTION_URL}?${params.toString()}`);
  },

  createBudgetExecution: async (dto: CreateBudgetExecutionDTO): Promise<BudgetExecutionDTO> => {
    return api.post<BudgetExecutionDTO>(BUDGET_EXECUTION_URL, dto);
  },

  exportBudgetExecution: async (format: 'pdf' | 'xlsx'): Promise<void> => {
    const response = await api.get('/reports/budget/execution/export', {
      params: { format },
      responseType: 'blob',
    });
    const url = window.URL.createObjectURL(new Blob([response as any]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `budget_execution.${format}`);
    document.body.appendChild(link);
    link.click();
    link.remove();
  },
};
