import type {
    GiteaSettings,
    GiteaSettingsWrite,
    GiteaRepository,
    GiteaBranch,
    GiteaBranchCreate,
    GiteaPullRequest,
    GiteaBranchName,
    GiteaTestResult,
} from './dto/gitea'
import type { HydraCollection } from '~/utils/api'
import { extractHydraMembers } from '~/utils/api'

export function useGiteaService() {
    const api = useApi()

    async function getSettings(): Promise<GiteaSettings> {
        return api.get<GiteaSettings>('/settings/gitea')
    }

    async function saveSettings(payload: GiteaSettingsWrite): Promise<GiteaSettings> {
        return api.put<GiteaSettings>('/settings/gitea', payload as Record<string, unknown>, {
            toastSuccessKey: 'gitea.settings.saved',
        })
    }

    async function testConnection(): Promise<GiteaTestResult> {
        return api.post<GiteaTestResult>('/settings/gitea/test')
    }

    async function listRepositories(): Promise<GiteaRepository[]> {
        const data = await api.get<HydraCollection<GiteaRepository>>('/gitea/repositories')
        return extractHydraMembers(data)
    }

    async function listBranches(taskId: number): Promise<GiteaBranch[]> {
        const data = await api.get<HydraCollection<GiteaBranch>>(`/tasks/${taskId}/gitea/branches`)
        return extractHydraMembers(data)
    }

    async function createBranch(taskId: number, payload: GiteaBranchCreate): Promise<GiteaBranch> {
        return api.post<GiteaBranch>(`/tasks/${taskId}/gitea/branches`, payload as Record<string, unknown>, {
            toastSuccessKey: 'gitea.branch.created',
        })
    }

    async function listPullRequests(taskId: number): Promise<GiteaPullRequest[]> {
        const data = await api.get<HydraCollection<GiteaPullRequest>>(`/tasks/${taskId}/gitea/pull-requests`)
        return extractHydraMembers(data)
    }

    async function getBranchName(taskId: number, type: string): Promise<GiteaBranchName> {
        return api.get<GiteaBranchName>(`/tasks/${taskId}/gitea/branch-name/${type}`)
    }

    return {
        getSettings,
        saveSettings,
        testConnection,
        listRepositories,
        listBranches,
        createBranch,
        listPullRequests,
        getBranchName,
    }
}
