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

export const SETTINGS_ROUTES = {
    INDEX: "/api/settings",
} as const satisfies Record<string, ApiPath>

export type SettingsUpdatePayload = {
    name?: string
    email?: string
    phone?: string
    alternative_phone?: string
    website?: string
    time_zone?: string
    upi_id?: string
    first_day_of_work?: string
    latitude?: string | number
    longitude?: string | number
    bank_details?: string
    first_address_line?: string
    second_address_line?: string
    country_id?: number | string
    state_id?: number | string
    city?: string
    zip_code?: string
    description?: string
    security?: string
    privacy_policy?: string
    logo?: File | null
}

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

    async fetch() {
        return this.get(SETTINGS_ROUTES.INDEX)
    }

    async update(payload: SettingsUpdatePayload) {
        const hasFile = payload && (payload as any).logo instanceof File
        if (!hasFile) {
            const { logo: _logo, ...rest } = (payload ?? {}) as Record<string, unknown>
            return this.put(SETTINGS_ROUTES.INDEX, rest as any)
        }

        const fd = new FormData()
        for (const [key, value] of Object.entries(payload as Record<string, unknown>)) {
            if (value === undefined || value === null) continue
            if (value instanceof File) {
                fd.append(key, value)
            } else {
                fd.append(key, String(value))
            }
        }
        fd.append("_method", "PUT")
        return this.postFormData(SETTINGS_ROUTES.INDEX, fd)
    }
}
