import {AxiosResponse} from "axios";
import {instance} from "./axios";
import {
    Vevaiosi, StoredVevaiosiFile, VevaiosiFileSyncBody, VevaiosiLookups, VevaiosiPayload,
    VevaiosiPaymentProgress, VevaiosiSaveParams, statusUiType
} from "../models/Ked/Vevaiosi";

// Only GET and POST: writes and deletes are POSTs to action-named routes.
type Method = 'GET' | 'POST';

/* -------------------------------- routes -------------------------------- */
// Single source of truth for every backend path. All under /api/gov_ked/v1 (EgovKedController).
// Ids never sit in the URL on the real routes: update / delete carry the id in the body.

const BASE = '/api/gov_ked/v1';

const ROUTES = {
    ping: `${BASE}/ping`,                                   // GET
    // one route for every lookup; ?types= picks which ones (none = all)
    lookups: `${BASE}/lookups`,                             // GET (getLookupTable)  form: ?types=kae,relations,signers · list: ?types=statuses
    signersDeclare: `${BASE}/signers/declare`,              // POST
    list: `${BASE}/certifiedDebts/list`,                    // POST
    // the single-record route, despite the name (getBeveosiStatus returns one whole vevaiosi)
    single: `${BASE}/certifiedDebts/status`,                // GET  GUESS: id as ?id=
    create: `${BASE}/certifiedDebts/add`,                   // POST (KedSubmissionController@store)
    update: `${BASE}/certifiedDebts/update`,                // POST (saveBeveosiDraft), id in body
    submit: `${BASE}/certifiedDebts/submit`,                // POST (KedSubmissionController@submit)
    remove: `${BASE}/certifiedDebts/delete`,                // POST, id in body
    paymentProgress: `${BASE}/certifiedDebts/paymentProgress`, // POST (getPaymentProgress), {auditProtocol, afm}

    // a stored record's files (KedSubmissionController); the backend finds every file by uuid in the stored record
    fileUpload: (id: number) => `${BASE}/certifiedDebts/${id}/files/upload`,         // POST: existing[], new{title,name,size,file}
    fileDelete: (id: number) => `${BASE}/certifiedDebts/${id}/files/delete`,         // POST: existing[], delete{uuid,title,name,size}
    fileDownload: (id: number) => `${BASE}/certifiedDebts/${id}/files/download`,     // POST {uuid} -> the file (blob)
};

/* -------------------------------- lookups -------------------------------- */
const FORM_LOOKUP_TYPES = ['kae', 'relations', 'signers'];
const LIST_LOOKUP_TYPES = ['statuses'];
const lookupsQuery = (types: string[]) => ({types: types.join(',')});

/* ----------------------------- status options ----------------------------- */

type RawStatusOption = { value: string; name?: string; label?: string };
const toStatusOption = (s: RawStatusOption) => ({
    value: s.value,
    name: s.name ?? s.label ?? s.value,
    ui_type: statusUiType(s.value),
});

/* ----------------------------- form lookups ------------------------------ */

type RawRelation = { code: string; category: string; label: string; categoryLabel: string };
type RawKedLookups = {
    relations?: RawRelation[];
    kae?: { kae: string; description: string }[];
    signers?: { afm: string; firstName: string; lastName: string; fullName: string }[];
};

// relation code -> category. The form only picks a relation; `category` follows from it.
// signer AFM -> full name, so nameYpogr can go along with afmYpogr.
// Both are filled every time the form lookups load and read by toWireParams on save.
let relationCategory: Record<string, string> = {};
let signerName: Record<string, string> = {};

const toFormLookups = (raw: RawKedLookups): VevaiosiLookups => {
    relationCategory = Object.fromEntries((raw?.relations ?? []).map(r => [r.code, r.category]));
    signerName = Object.fromEntries((raw?.signers ?? []).map(s => [s.afm, s.fullName]));
    return {
        kae: (raw?.kae ?? []).map(k => ({value: Number(k.kae), name: `${k.kae} - ${k.description}`})),
        relations: (raw?.relations ?? []).map(r => ({value: Number(r.code), name: r.label})),
        signatories: (raw?.signers ?? []).map(s => ({value: s.afm, name: `${s.fullName} ( ${s.afm} )`})),
    };
};

/* --------------------------- payment progress --------------------------- */

type RawPaymentProgress = {
    payId?: string | null;
    afm?: string | null;
    fullName?: string | null;
    auditProtocol?: string | null;
    apofNoEtos?: string | null;
    sunolo?: string | number | null;
    firstEstablishedAmount?: string | number | null;
    paidAmount?: string | number | null;
    deletedAmount?: string | number | null;
    reducedAmount?: string | number | null;
    restAmount?: string | number | null;
    overdueAmount?: string | number | null;
    totalAmount?: string | number | null;
    callSequenceId?: string | number | null;
    callSequenceDate?: string | null;
};

type PaymentProgressEnvelope = {
    data?: RawPaymentProgress | null;
    errors?: unknown;
    status?: number;
};

const decimalOrNull = (v: string | number | null | undefined) => {
    if (v == null || v === '') return null;
    const n = Number(v);
    return Number.isNaN(n) ? String(v) : n.toFixed(2);
};

const textOrNull = (v: string | number | null | undefined) => (v == null || v === '' ? null : String(v));

const toPaymentProgress = (raw?: RawPaymentProgress | null): VevaiosiPaymentProgress => ({
    debtId: textOrNull(raw?.payId),
    originalAmount: decimalOrNull(raw?.firstEstablishedAmount),
    reducedAmount: decimalOrNull(raw?.reducedAmount),
    paidAmount: decimalOrNull(raw?.paidAmount),
    balance: decimalOrNull(raw?.restAmount),
    writtenOffAmount: decimalOrNull(raw?.deletedAmount),
    overdueAmount: decimalOrNull(raw?.overdueAmount),
    kedUpdatedAt: raw?.callSequenceDate ?? null,
    kedRef: textOrNull(raw?.callSequenceId),
});

const hasErrors = (errors: unknown) =>
    errors != null && errors !== '' && !(Array.isArray(errors) && errors.length === 0)
    && !(typeof errors === 'object' && !Array.isArray(errors) && Object.keys(errors as object).length === 0);

/* ---------------------------- wire format ---------------------------- */

const money = (n: number) => n.toFixed(2);

type LocalFile = { title: string; file: File };

type WireParams = Omit<VevaiosiSaveParams, 'sunolo' | 'kaeLines' | 'synypochreoi' | 'phone'> & {
    sunolo: string;
    kaeLines: { kae: string; amount: string }[];
    synypochreoi: { afm: string; fullName: string; code: string; category: string }[];
    debtorPhone: string;
    nameYpogr: string | null;
};

const toWireParams = ({phone, ...p}: VevaiosiSaveParams): WireParams => ({
    ...p,
    debtorPhone: phone,
    nameYpogr: signerName[p.afmYpogr] ?? null,
    sunolo: money(p.sunolo),
    kaeLines: p.kaeLines.map(l => ({kae: String(l.kae), amount: money(l.amount)})),
    synypochreoi: p.synypochreoi.map(({relation, ...c}) => {
        const code = String(relation);
        return {...c, code, category: relationCategory[code] ?? ''};
    }),
});

const buildCreateFormData = (data: WireParams, files: LocalFile[]) => {
    const fd = new FormData();
    Object.entries(data).forEach(([key, value]) => appendNested(fd, key, value));
    files.forEach((f, i) => {
        fd.append(`file[${i}][title]`, f.title ?? '');
        fd.append(`file[${i}][file]`, f.file);
    });
    return fd;
};

const appendNested = (fd: FormData, key: string, value: unknown) => {
    if (value instanceof File) fd.append(key, value);
    else if (Array.isArray(value)) value.forEach((v, i) => appendNested(fd, `${key}[${i}]`, v));
    else if (value !== null && typeof value === 'object') {
        Object.entries(value).forEach(([k, v]) => appendNested(fd, `${key}[${k}]`, v));
    } else if (typeof value === 'boolean') fd.append(key, value ? '1' : '0');
    else if (value != null) fd.append(key, String(value));
};

const buildFilesSyncFormData = (body: VevaiosiFileSyncBody) => {
    const fd = new FormData();
    appendNested(fd, 'existing', body.existing);
    if ('new' in body) appendNested(fd, 'new', body.new);
    else appendNested(fd, 'delete', body.delete);
    return fd;
};

/* ------------------------------- API calls ------------------------------ */

// GET /ping: connectivity / auth check against the gov_ked service
export async function pingKed() {
    return instance.get(ROUTES.ping);
}

export async function getVevaioseis(params: any) {
    return instance.post(ROUTES.list, params);
}

// GET /certifiedDebts/status (getBeveosiStatus): returns one whole vevaiosi.
export async function getSingleVevaiosi(id: number | string) {
    return instance.get<Vevaiosi>(ROUTES.single, {params: {id: Number(id)}});
}

// List lookups: GET /lookups?types=statuses
export async function getVevaioseisLookups() {
    const res = await instance.get<{ statuses?: RawStatusOption[] }>(ROUTES.lookups, {params: lookupsQuery(LIST_LOOKUP_TYPES)});
    return {...res, data: {statuses: (res.data?.statuses ?? []).map(toStatusOption)}};
}

// POST /certifiedDebts/delete, body {id}
export async function deleteVevaiosi(id: number) {
    return instance.post(ROUTES.remove, {id});
}

/**
 * POST /certifiedDebts/paymentProgress (getPaymentProgress)
 */
export async function getPaymentProgress(
    auditProtocol: string, afm: string, audit?: { auditUserId?: string; auditUserIp?: string }
): Promise<AxiosResponse<VevaiosiPaymentProgress>> {
    const body = {auditProtocol, afm, ...(audit ?? {})};
    const res = await instance.post<PaymentProgressEnvelope | RawPaymentProgress>(ROUTES.paymentProgress, body);
    const envelope = res.data as PaymentProgressEnvelope;
    if ((envelope?.status !== undefined && envelope.status !== 1) || hasErrors(envelope?.errors)) {
        throw {response: {...res, data: envelope}};
    }
    const record = envelope?.data && typeof envelope.data === 'object'
        ? envelope.data
        : res.data as RawPaymentProgress;
    return {...res, data: toPaymentProgress(record)};
}

// POST /signers/declare
export async function declareSigners(body: any) {
    return instance.post(ROUTES.signersDeclare, body);
}

// Form dropdowns: GET /lookups?types=kae,relations,signers
export async function getVevaiosiFormLookups(): Promise<AxiosResponse<VevaiosiLookups>> {
    const res = await instance.get<RawKedLookups>(ROUTES.lookups, {params: lookupsQuery(FORM_LOOKUP_TYPES)});
    return {...res, data: toFormLookups(res.data)};
}

/**
 * Create (no id) or update (id) a draft or rejected record, and optionally send it to ΚΕΔ.
 *   submit: false, no id -> POST /certifiedDebts/add
 *   submit: false, id    -> POST /certifiedDebts/update
 *   submit: true         -> POST /certifiedDebts/submit
 */
export async function saveVevaiosi(
    payload: VevaiosiPayload, id?: number | null, files?: LocalFile[], submit = false
): Promise<AxiosResponse<{ id: number }>> {
    const url = submit ? ROUTES.submit : id ? ROUTES.update : ROUTES.create;
    const params = toWireParams({...payload, submit});
    const request = id ? {...params, id} : params;
    const body = !id && files?.length ? buildCreateFormData(params, files) : request;
    return instance.post(url, body);
}

/**
 * POST /certifiedDebts/{id}/files/download, body {uuid}: one stored file, as a blob.
 */
export async function downloadVevaiosiFile(id: number, uuid: string): Promise<AxiosResponse<Blob>> {
    return instance.post<Blob>(ROUTES.fileDownload(id), {uuid}, {responseType: 'blob'});
}

/**
 * Add or delete a file on an existing record.
 * - upload  POST .../files/upload
 * - delete  POST .../files/delete
 */
export async function syncVevaiosiFiles(
    id: number, body: VevaiosiFileSyncBody
): Promise<AxiosResponse<StoredVevaiosiFile[]>> {
    const url = 'new' in body ? ROUTES.fileUpload(id) : ROUTES.fileDelete(id);
    return instance.post(url, buildFilesSyncFormData(body));
}
