// ═══════════════════════════════════════════════════════════════════════
// Audit Documents — API client (mirrors previous-nc.api.ts upload pattern)
// ═══════════════════════════════════════════════════════════════════════

const API_BASE =
  process.env.NEXT_PUBLIC_API_URL?.replace(/\/api$/, '') ||
  process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/api$/, '') ||
  '';

export type AuditDocType =
  | 'stage1_report'
  | 'stage2_report'
  | 'attendance'
  | 'nc_form'
  | 'support_docs';

// same token logic as previous-nc.api.ts
function getAuthToken(): string {
  if (typeof window === 'undefined') return '';
  return (
    localStorage.getItem('access_token') ||
    sessionStorage.getItem('access_token') ||
    localStorage.getItem('token') ||
    localStorage.getItem('authToken') ||
    ''
  );
}

function authHeaders(): HeadersInit {
  const token = getAuthToken();
  return token ? { Authorization: `Bearer ${token}` } : {};
}

export interface UploadAuditDocResponse {
  ok: true;
  row_id: number;
  doc_type: string;
  document_path: string;
  filename: string;
  size: number;
}

// XHR upload with progress — same shape as uploadEntryEvidence
export async function uploadAuditDocument(
  rowId: number,
  docType: AuditDocType,
  file: File,
  onProgress?: (percent: number) => void,
): Promise<UploadAuditDocResponse> {
  const url = `${API_BASE}/api/audits/${rowId}/documents`;

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    formData.append('file', file);
    formData.append('doc_type', docType);

    xhr.open('POST', url);

    const token = getAuthToken();
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`);
    }

    // 1 GB uploads can take a while — no timeout
    xhr.timeout = 0;

    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable && onProgress) {
        onProgress(Math.round((e.loaded / e.total) * 100));
      }
    };

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          resolve(JSON.parse(xhr.responseText));
        } catch {
          reject(new Error('Invalid response from server'));
        }
      } else {
        let msg = `Upload failed: ${xhr.status} ${xhr.statusText}`;
        try {
          const body = JSON.parse(xhr.responseText);
          if (body?.message) {
            msg = Array.isArray(body.message) ? body.message.join('; ') : body.message;
          }
        } catch {}
        reject(new Error(msg));
      }
    };

    xhr.onerror = () => reject(new Error('Network error during upload'));
    xhr.onabort = () => reject(new Error('Upload aborted'));

    xhr.send(formData);
  });
}

// Stream/view an uploaded document as a blob URL (same as fetchEntryFileBlob)
export async function fetchAuditDocumentBlob(
  rowId: number,
  docType: AuditDocType,
): Promise<string> {
  const url = `${API_BASE}/api/audits/${rowId}/documents/${docType}`;
  const res = await fetch(url, { headers: authHeaders() });
  if (!res.ok) {
    let detail = '';
    try {
      detail = (await res.json())?.message || '';
    } catch {}
    throw new Error(
      `Failed to fetch document: ${res.status} ${res.statusText}${detail ? ` — ${detail}` : ''}`,
    );
  }
  const blob = await res.blob();
  return URL.createObjectURL(blob);
}