import { api, PageResponse } from './api';
import { MinistryDTO, OrgUnitDTO, PositionDTO } from '../types/org';

class OrgService {
    // --- Ministries ---
    async getMinistries(params?: any): Promise<PageResponse<MinistryDTO>> {
        return api.getPage<MinistryDTO>('/org/ministries', params);
    }

    async getMinistryById(id: string): Promise<MinistryDTO> {
        return api.get<MinistryDTO>(`/org/ministries/${id}`);
    }

    async createMinistry(data: MinistryDTO): Promise<MinistryDTO> {
        return api.post<MinistryDTO>('/org/ministries', data);
    }

    async updateMinistry(id: string, data: MinistryDTO): Promise<MinistryDTO> {
        return api.put<MinistryDTO>(`/org/ministries/${id}`, data);
    }

    async deleteMinistry(id: string): Promise<void> {
        return api.delete(`/org/ministries/${id}`);
    }

    // --- Org Units ---
    async getOrgUnits(params?: any): Promise<PageResponse<OrgUnitDTO>> {
        return api.getPage<OrgUnitDTO>('/org/org-units', params);
    }

    async getOrgUnitTree(ministryId: string): Promise<OrgUnitDTO[]> {
        return api.get<OrgUnitDTO[]>(`/org/org-units/tree/${ministryId}`);
    }

    async getOrgUnitById(id: string): Promise<OrgUnitDTO> {
        return api.get<OrgUnitDTO>(`/org/org-units/${id}`);
    }

    async createOrgUnit(data: OrgUnitDTO): Promise<OrgUnitDTO> {
        return api.post<OrgUnitDTO>('/org/org-units', data);
    }

    async updateOrgUnit(id: string, data: OrgUnitDTO): Promise<OrgUnitDTO> {
        return api.put<OrgUnitDTO>(`/org/org-units/${id}`, data);
    }

    // --- Positions ---
    async getPositions(params?: any): Promise<PageResponse<PositionDTO> | PositionDTO[]> {
        // O controller retorna List se orgUnitId for passado, ou Page se não for.
        // O método getPage do api.ts espera PageResponse.
        // Se precisarmos suportar o retorno de lista, teremos que ajustar ou usar api.get diretamente.
        // Por simplicidade, vamos assumir o uso paginado por padrão na listagem geral.
        if (params?.orgUnitId) {
            return api.get<PositionDTO[]>('/org/positions', { params }) as any;
        }
        return api.getPage<PositionDTO>('/org/positions', params);
    }

    async getPositionById(id: string): Promise<PositionDTO> {
        return api.get<PositionDTO>(`/org/positions/${id}`);
    }

    async createPosition(data: PositionDTO): Promise<PositionDTO> {
        return api.post<PositionDTO>('/org/positions', data);
    }

    async updatePosition(id: string, data: PositionDTO): Promise<PositionDTO> {
        return api.put<PositionDTO>(`/org/positions/${id}`, data);
    }
}

export const orgService = new OrgService();
