import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

class ApiClient {
    private client: AxiosInstance

    constructor() {
        this.client = axios.create({
            withCredentials: true,
            headers: {
                'Content-Type': 'application/json',
            },
        })
    }

    private getCsrfToken(): string {
        let cookieValue = ''
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';')
            for (const rawCookie of cookies) {
                const cookie = (rawCookie || '').trim()
                if (cookie.startsWith('csrftoken=')) {
                    cookieValue = decodeURIComponent(cookie.slice('csrftoken='.length))
                    break
                }
            }
        }
        return cookieValue
    }

    private withCsrf(config?: AxiosRequestConfig): AxiosRequestConfig {
        const token = this.getCsrfToken()
        const csrfHeader = token ? { 'X-CSRFToken': token } : {}
        return {
            ...config,
            headers: {
                ...csrfHeader,
                ...(config?.headers || {}),
            },
        }
    }

    processUrl(endpoint: string): string {
        return `${apiEndpoint}${endpoint}`
    }

    get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
        return this.client.get<T>(this.processUrl(url), this.withCsrf(config))
    }

    post<T = unknown>(
        url: string,
        data?: unknown,
        config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> {
        return this.client.post<T>(this.processUrl(url), data, this.withCsrf(config))
    }

    put<T = unknown>(
        url: string,
        data?: unknown,
        config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> {
        return this.client.put<T>(this.processUrl(url), data, this.withCsrf(config))
    }

    patch<T = unknown>(
        url: string,
        data?: unknown,
        config?: AxiosRequestConfig,
    ): Promise<AxiosResponse<T>> {
        return this.client.patch<T>(this.processUrl(url), data, this.withCsrf(config))
    }

    delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
        return this.client.delete<T>(this.processUrl(url), this.withCsrf(config))
    }
}

export const apiEndpoint = '/api/';

export const API = {
    auth: {
        me: () => 'user/me/',
        login: () => 'user/login/',
        logout: () => 'user/logout/',
        session: () => 'user/session/',
        signup: () => 'user/signup/',
        changePassword: () => 'user/change_password/',
    },

    organization: {
        list: () => 'organization/',
        byId: (uuid: string) => `organization/${uuid}/`,
        members: {
            list: (uuid: string) => `organization/${uuid}/members/`,
            remove: (uuid: string, userUuid: string) =>
                `organization/${uuid}/member/${userUuid}/remove/`,
        },
        invites: {
            list: (uuid: string) => `organization/${uuid}/invite/`,
            create: (uuid: string, maxUses: number) =>
                `organization/${uuid}/create-invite/?max_uses=${maxUses}`,
            revoke: (uuid: string, inviteUuid: string) =>
                `organization/${uuid}/revoke-invite/${inviteUuid}/`,
            join: (inviteUuid: string) => `organization/join/${inviteUuid}/`,
        },
        leave: (uuid: string) => `organization/${uuid}/leave/`,
        roles: {
            list: (uuid: string) => `organization/${uuid}/role/`,
            mine: () => 'organization/role/mine/',
            remove: (orgUuid: string, roleUuid: string) =>
                `organization/${orgUuid}/role/${roleUuid}/`,
            join: (orgUuid: string, roleUuid: string) =>
                `organization/${orgUuid}/role/${roleUuid}/join/`,
        },
    },

    knowledge: {
        trainingFiles: {
            list: () => 'training-file/',
            byId: (uuid: string) => `training-file/${uuid}/`,
        },
        roleRagDocuments: {
            list: () => 'role-rag-document/',
            byId: (uuid: string) => `role-rag-document/${uuid}/`,
        },
    },

    agents: {
        configs: {
            list: () => 'agent-config/',
            byId: (uuid: string) => `agent-config/${uuid}/`,
        },
    },

    onboarding: {
        flows: {
            list: () => 'onboarding-flow/',
            byId: (uuid: string) => `onboarding-flow/${uuid}/`,
            startSession: (uuid: string) => `onboarding-flow/${uuid}/start-session/`,
        },
        sessions: {
            list: () => 'onboarding-session/',
            byId: (uuid: string) => `onboarding-session/${uuid}/`,
            interact: (uuid: string) => `onboarding-session/${uuid}/interact/`,
            history: (uuid: string) => `onboarding-session/${uuid}/history/`,
            complete: (uuid: string) => `onboarding-session/${uuid}/complete/`,
        },
        logs: {
            list: () => 'agent-interaction-log/',
            byId: (uuid: string) => `agent-interaction-log/${uuid}/`,
        },
    },
}
export const apiClient = new ApiClient()
export { isAxiosError } from 'axios'
