import type { ApprovalCase, VerificationCase } from './types';
import type { CrudRecord } from './types';

type ApiResponse<T> = { success: boolean; data: T; error?: string };

async function parse<T>(res: Response): Promise<T> {
  const payload = (await res.json().catch(() => null)) as ApiResponse<T> | T | null;
  if (!res.ok) {
    const message = (payload as ApiResponse<T> | null)?.error || `Request failed (${res.status})`;
    throw new Error(message);
  }
  if (payload && typeof payload === 'object' && 'success' in (payload as any)) {
    return (payload as ApiResponse<T>).data;
  }
  return payload as T;
}

export async function listVerificationCases(query?: { q?: string; status?: string }) {
  const qp = new URLSearchParams();
  if (query?.q) qp.set('q', query.q);
  if (query?.status) qp.set('status', query.status);
  const res = await fetch(`/api/admin/verification-cases${qp.toString() ? `?${qp.toString()}` : ''}`);
  return parse<VerificationCase[]>(res);
}

export async function bulkVerification(ids: string[], action: string) {
  const res = await fetch('/api/admin/verification-cases/bulk', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids, action }),
  });
  return parse<{ ok: boolean; count: number }>(res);
}

export async function updateVerification(id: string, patch: Partial<VerificationCase>) {
  const res = await fetch(`/api/admin/verification-cases/${encodeURIComponent(id)}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch),
  });
  return parse<VerificationCase>(res);
}

export async function listApprovalCases(query?: { q?: string; status?: string }) {
  const qp = new URLSearchParams();
  if (query?.q) qp.set('q', query.q);
  if (query?.status) qp.set('status', query.status);
  const res = await fetch(`/api/admin/approval-cases${qp.toString() ? `?${qp.toString()}` : ''}`);
  return parse<ApprovalCase[]>(res);
}

export async function bulkApproval(ids: string[], action: string) {
  const res = await fetch('/api/admin/approval-cases/bulk', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids, action }),
  });
  return parse<{ ok: boolean; count: number }>(res);
}

export async function updateApproval(id: string, patch: Partial<ApprovalCase>) {
  const res = await fetch(`/api/admin/approval-cases/${encodeURIComponent(id)}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch),
  });
  return parse<ApprovalCase>(res);
}

export async function listModuleRecords<T extends CrudRecord = CrudRecord>(moduleKey: string, query?: { q?: string; status?: string }) {
  const qp = new URLSearchParams();
  if (query?.q) qp.set('q', query.q);
  if (query?.status) qp.set('status', query.status);
  const res = await fetch(`/api/admin/modules/${encodeURIComponent(moduleKey)}/records${qp.toString() ? `?${qp.toString()}` : ''}`);
  return parse<T[]>(res);
}

export async function createModuleRecord<T extends CrudRecord = CrudRecord>(moduleKey: string, payload: Partial<T>) {
  const res = await fetch(`/api/admin/modules/${encodeURIComponent(moduleKey)}/records`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  return parse<T>(res);
}

export async function updateModuleRecord<T extends CrudRecord = CrudRecord>(moduleKey: string, id: string, patch: Partial<T>) {
  const res = await fetch(`/api/admin/modules/${encodeURIComponent(moduleKey)}/records/${encodeURIComponent(id)}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch),
  });
  return parse<T>(res);
}

export async function deleteModuleRecord(moduleKey: string, id: string) {
  const res = await fetch(`/api/admin/modules/${encodeURIComponent(moduleKey)}/records/${encodeURIComponent(id)}`, {
    method: 'DELETE',
  });
  return parse<{ ok: boolean; id: string }>(res);
}

export async function bulkModuleRecordAction(moduleKey: string, ids: string[], action: string) {
  const res = await fetch(`/api/admin/modules/${encodeURIComponent(moduleKey)}/records/bulk`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids, action }),
  });
  return parse<{ ok: boolean; count: number }>(res);
}
