import { ApiClient, ApiError, type ApiClientOptions } from "../infra/client"
import type { ApiPath } from "../infra/types"

export const DOCUMENT_SHARE_ROUTES = {
    STORE: "/api/documents/share",
} as const satisfies Record<string, ApiPath>

export type DocumentShareType =
    | "inspection"
    | "estimate"
    | "job_card"
    | "invoice"
    | "payment_received"
    | "purchase_order"
    | "bill"
    | string

export type DocumentShareChannel = "email" | "link"

export interface DocumentSharePayload {
    document_type: DocumentShareType
    document_id: number | string
    channel: DocumentShareChannel
    email?: string
    phone?: string
    message?: string
}

export interface DocumentShareResponse {
    share_url: string
    whatsapp_url: string
    expires_at: string | null
}

export class DocumentShareClient extends ApiClient {
    constructor(baseUrl?: string, defaultOptions?: ApiClientOptions) {
        super(baseUrl, defaultOptions)
    }

    async share(payload: DocumentSharePayload): Promise<DocumentShareResponse> {
        const endpoint = DOCUMENT_SHARE_ROUTES.STORE
        const url = `${this.baseUrl.replace(/\/+$/, "")}${endpoint}`
        const headers = new Headers(this.defaultOptions.headers as Record<string, string>)
        headers.set("Accept", "application/json")
        headers.set("Content-Type", "application/json")

        const body = { ...payload, document_id: Number(payload.document_id) }
        const response = await fetch(url, {
            method: "POST",
            headers,
            body: JSON.stringify(body),
        })

        const text = await response.text()
        const data = text ? JSON.parse(text) : null

        if (!response.ok) {
            throw new ApiError(response.status, response.statusText, endpoint, "post", data)
        }

        return data as DocumentShareResponse
    }
}
