'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { BillRecord, BillApiData, BillStatus } from './types';
import { transformApiToFrontend, transformFrontendToApi } from './types';

// ===== API 응답 타입 =====
interface BillSummaryApiData {
  total_amount: number;
  total_count: number;
  by_type: Record<string, { total: number; count: number }>;
  by_status: Record<string, { total: number; count: number }>;
  maturity_alert_amount: number;
}

// ===== 어음 목록 조회 =====
export async function getBills(params: {
  search?: string; billType?: string; status?: string; clientId?: string;
  isElectronic?: boolean; instrumentType?: string; medium?: string;
  issueStartDate?: string; issueEndDate?: string;
  maturityStartDate?: string; maturityEndDate?: string;
  sortBy?: string; sortDir?: string; perPage?: number; page?: number;
}) {
  return executePaginatedAction<BillApiData, BillRecord>({
    url: buildApiUrl('/api/v1/bills', {
      search: params.search,
      bill_type: params.billType && params.billType !== 'all' ? params.billType : undefined,
      status: params.status && params.status !== 'all' ? params.status : undefined,
      client_id: params.clientId,
      is_electronic: params.isElectronic,
      instrument_type: params.instrumentType && params.instrumentType !== 'all' ? params.instrumentType : undefined,
      medium: params.medium && params.medium !== 'all' ? params.medium : undefined,
      issue_start_date: params.issueStartDate,
      issue_end_date: params.issueEndDate,
      maturity_start_date: params.maturityStartDate,
      maturity_end_date: params.maturityEndDate,
      sort_by: params.sortBy,
      sort_dir: params.sortDir,
      per_page: params.perPage,
      page: params.page,
    }),
    transform: transformApiToFrontend,
    errorMessage: '어음 목록 조회에 실패했습니다.',
  });
}

// ===== 어음 상세 조회 =====
export async function getBill(id: string): Promise<ActionResult<BillRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bills/${id}`),
    transform: (data: BillApiData) => transformApiToFrontend(data),
    errorMessage: '어음 조회에 실패했습니다.',
  });
}

// ===== 어음 등록 =====
export async function createBill(data: Partial<BillRecord>): Promise<ActionResult<BillRecord>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bills'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (d: BillApiData) => transformApiToFrontend(d),
    errorMessage: '어음 등록에 실패했습니다.',
  });
}

// ===== 어음 수정 =====
export async function updateBill(id: string, data: Partial<BillRecord>): Promise<ActionResult<BillRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bills/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (d: BillApiData) => transformApiToFrontend(d),
    errorMessage: '어음 수정에 실패했습니다.',
  });
}

// ===== 어음 삭제 =====
export async function deleteBill(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bills/${id}`),
    method: 'DELETE',
    errorMessage: '어음 삭제에 실패했습니다.',
  });
}

// ===== 어음 상태 변경 =====
export async function updateBillStatus(id: string, status: BillStatus): Promise<ActionResult<BillRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bills/${id}/status`),
    method: 'PATCH',
    body: { status },
    transform: (data: BillApiData) => transformApiToFrontend(data),
    errorMessage: '어음 상태 변경에 실패했습니다.',
  });
}

// ===== 어음 요약 조회 =====
export async function getBillSummary(params: {
  billType?: string; issueStartDate?: string; issueEndDate?: string;
  maturityStartDate?: string; maturityEndDate?: string;
}): Promise<ActionResult<{
  totalAmount: number; totalCount: number;
  byType: Record<string, { total: number; count: number }>;
  byStatus: Record<string, { total: number; count: number }>;
  maturityAlertAmount: number;
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bills/summary', {
      bill_type: params.billType && params.billType !== 'all' ? params.billType : undefined,
      issue_start_date: params.issueStartDate,
      issue_end_date: params.issueEndDate,
      maturity_start_date: params.maturityStartDate,
      maturity_end_date: params.maturityEndDate,
    }),
    transform: (data: BillSummaryApiData) => ({
      totalAmount: data.total_amount,
      totalCount: data.total_count,
      byType: data.by_type,
      byStatus: data.by_status,
      maturityAlertAmount: data.maturity_alert_amount,
    }),
    errorMessage: '어음 요약 조회에 실패했습니다.',
  });
}

// ===== V8: 어음 상세 조회 (BillApiData 그대로 반환) =====
export async function getBillRaw(id: string): Promise<ActionResult<BillApiData>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bills/${id}`),
    errorMessage: '어음 조회에 실패했습니다.',
  });
}

// ===== V8: 어음 등록 (raw payload) =====
export async function createBillRaw(data: Record<string, unknown>): Promise<ActionResult<BillApiData>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bills'),
    method: 'POST',
    body: data,
    errorMessage: '어음 등록에 실패했습니다.',
  });
}

// ===== V8: 어음 수정 (raw payload) =====
export async function updateBillRaw(id: string, data: Record<string, unknown>): Promise<ActionResult<BillApiData>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bills/${id}`),
    method: 'PUT',
    body: data,
    errorMessage: '어음 수정에 실패했습니다.',
  });
}

// ===== 거래처 목록 조회 =====
export async function getClients(): Promise<ActionResult<{ id: number; name: string }[]>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/clients', { size: 1000 }),
    transform: (data: { data?: { id: number; name: string }[] } | { id: number; name: string }[]) => {
      type ClientApi = { id: number; name: string };
      const clients: ClientApi[] = Array.isArray(data) ? data : (data as { data?: ClientApi[] })?.data || [];
      return clients.map(c => ({ id: c.id, name: c.name }));
    },
    errorMessage: '거래처 조회에 실패했습니다.',
  });
}
