/**
 * Image / video upload — ImgBB or Daiman Shop API.
 * - ImgBB: https://api.imgbb.com/ — POST multipart "image", query ?key=
 * - Daiman: https://image.daiman.shop/api/upload.php — POST multipart "image", optional ?key= or X-API-Key
 *
 * Per-store: call setUploadConfig() when siteSettings loads (dashboard, inventory, etc.).
 */
export const UPLOAD_PROVIDER_IMGBB = 'imgbb';
export const UPLOAD_PROVIDER_DAIMAN = 'daiman';
export const UPLOAD_PROVIDER_PROXY = 'proxy';

export const DEFAULT_IMGBB_API_KEY = '';

/** @deprecated use DEFAULT_IMGBB_API_KEY */
export const IMAGE_UPLOAD_API_KEY = DEFAULT_IMGBB_API_KEY;

export const IMAGE_UPLOAD_BASE = 'https://api.imgbb.com/1/upload';

export const DAIMAN_UPLOAD_BASE = 'https://image.daiman.shop/api/upload.php';

let currentProvider = UPLOAD_PROVIDER_PROXY;
let imgbbKey = DEFAULT_IMGBB_API_KEY;
let daimanKey = '';
const LOCAL_UPLOAD_PROXY_BASE = 'api/image-upload-proxy.php';

/**
 * @param {string|null|undefined} provider 'imgbb' | 'daiman' (default imgbb)
 * @param {string|null|undefined} imgbbApiKey trimmed; empty uses default project ImgBB key
 * @param {string|null|undefined} daimanApiKey optional Daiman API key
 */
export function setUploadConfig(provider, imgbbApiKey, daimanApiKey) {
    const p = String(provider || '').trim().toLowerCase();
    if (p === UPLOAD_PROVIDER_DAIMAN) currentProvider = UPLOAD_PROVIDER_DAIMAN;
    else if (p === UPLOAD_PROVIDER_IMGBB) currentProvider = UPLOAD_PROVIDER_IMGBB;
    else currentProvider = UPLOAD_PROVIDER_PROXY;
    const ik = imgbbApiKey != null ? String(imgbbApiKey).trim() : '';
    imgbbKey = ik || DEFAULT_IMGBB_API_KEY;
    daimanKey = daimanApiKey != null ? String(daimanApiKey).trim() : '';
}

/**
 * @param {string|null|undefined} key trimmed; empty resets to default project key (ImgBB only)
 * @deprecated Prefer setUploadConfig; this only updates the ImgBB key and does not change provider.
 */
export function setCustomImgbbKey(key) {
    const t = key != null ? String(key).trim() : '';
    imgbbKey = t || DEFAULT_IMGBB_API_KEY;
}

export function getUploadUrl() {
    if (currentProvider === UPLOAD_PROVIDER_PROXY) {
        return LOCAL_UPLOAD_PROXY_BASE;
    }
    if (currentProvider === UPLOAD_PROVIDER_DAIMAN) {
        if (!daimanKey) return `${LOCAL_UPLOAD_PROXY_BASE}?provider=daiman`;
        return `${DAIMAN_UPLOAD_BASE}?key=${encodeURIComponent(daimanKey)}`;
    }
    if (!imgbbKey) {
        return LOCAL_UPLOAD_PROXY_BASE;
    }
    return `${IMAGE_UPLOAD_BASE}?key=${encodeURIComponent(imgbbKey)}`;
}

/** Success: data.data.url (ImgBB + Daiman); ImgBB also has display_url / nested image.url */
export function pickUploadPublicUrl(data) {
    const d = data && data.data;
    if (!d) return '';
    const u = d.url || d.display_url || (d.image && typeof d.image.url === 'string' ? d.image.url : '');
    return typeof u === 'string' ? u.trim() : '';
}

/**
 * Parse upload API JSON; return public URL or user-facing error.
 * @param {number} httpStatus
 * @param {string} responseText
 * @returns {{ ok: boolean, url: string, message: string }}
 */
export function interpretUploadResponse(httpStatus, responseText) {
    const raw = responseText != null ? String(responseText) : '';
    const text = raw.trim();
    let data = null;
    try {
        data = text ? JSON.parse(text) : null;
    } catch {
        const st = Number.isFinite(httpStatus) ? httpStatus : 0;
        const hint = st ? ` (HTTP ${st})` : '';
        return {
            ok: false,
            url: '',
            message: `আপলোড ব্যর্থ: সার্ভার অপ্রত্যাশিত উত্তর পাঠিয়েছে${hint}।`,
        };
    }

    const url = pickUploadPublicUrl(data);
    const statusOk = Number.isFinite(httpStatus) && httpStatus >= 200 && httpStatus < 300;
    const successFlag = data && data.success === true;

    if (statusOk && successFlag && url) {
        return { ok: true, url, message: '' };
    }

    const errObj = data && data.error;
    const errFromImgbb =
        errObj && typeof errObj.message === 'string'
            ? errObj.message.trim()
            : '';
    const statusTxt =
        data && typeof data.status_txt === 'string' ? data.status_txt.trim() : '';
    const topMessage =
        data && typeof data.message === 'string' ? data.message.trim() : '';

    let message = 'আপলোড ব্যর্থ।';
    if (statusOk && successFlag && !url) {
        message = 'আপলোড ব্যর্থ: সার্ভার ছবির URL পাঠায়নি।';
    } else if (errFromImgbb) {
        message = `আপলোড ব্যর্থ: ${errFromImgbb}`;
    } else if (topMessage) {
        message = `আপলোড ব্যর্থ: ${topMessage}`;
    } else if (statusTxt) {
        message = `আপলোড ব্যর্থ: ${statusTxt}`;
    } else if (!statusOk) {
        message = `আপলোড ব্যর্থ: HTTP ${Number.isFinite(httpStatus) ? httpStatus : 'error'}`;
    }

    const errCodeNested = errObj && errObj.code != null ? String(errObj.code) : '';
    const errCodeTop = data && data.code != null ? String(data.code) : '';
    const errCode = errCodeNested || errCodeTop;
    if (errCode && !message.includes(errCode)) {
        message += ` (${errCode})`;
    }

    return { ok: false, url: '', message };
}
