'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 { PaymentApiData, PaymentHistory } from './types';
import { transformApiToFrontend } from './utils';

// ===== API 응답 타입 =====
interface PaymentStatementApiData {
  statement_no: string;
  issued_at: string;
  payment: { id: number; amount: number; formatted_amount: string; payment_method: string; payment_method_label: string; transaction_id: string | null; status: string; status_label: string; paid_at: string | null; memo: string | null };
  subscription: { id: number; started_at: string | null; ended_at: string | null; status: string; status_label: string };
  plan: { id: number; name: string; code: string; price: number; billing_cycle: string; billing_cycle_label: string } | null;
  customer: { tenant_id: number; company_name: string; business_number: string | null; representative: string | null; address: string | null; email: string | null; phone: string | null };
  items: Array<{ description: string; quantity: number; unitPrice: number; amount: number }>;
  subtotal: number;
  tax: number;
  total: number;
}

interface StatementData {
  statementNo: string;
  issuedAt: string;
  payment: { id: number; amount: number; formattedAmount: string; paymentMethod: string; paymentMethodLabel: string; transactionId: string | null; status: string; statusLabel: string; paidAt: string | null; memo: string | null };
  subscription: { id: number; startedAt: string | null; endedAt: string | null; status: string; statusLabel: string };
  plan: { id: number; name: string; code: string; price: number; billingCycle: string; billingCycleLabel: string } | null;
  customer: { tenantId: number; companyName: string; businessNumber: string | null; representative: string | null; address: string | null; email: string | null; phone: string | null };
  items: Array<{ description: string; quantity: number; unitPrice: number; amount: number }>;
  subtotal: number;
  tax: number;
  total: number;
}

// ===== 결제 목록 조회 =====
export async function getPayments(params?: {
  page?: number; perPage?: number; status?: string; startDate?: string; endDate?: string; search?: string;
}) {
  return executePaginatedAction<PaymentApiData, PaymentHistory>({
    url: buildApiUrl('/api/v1/payments', {
      page: params?.page,
      per_page: params?.perPage,
      status: params?.status,
      start_date: params?.startDate,
      end_date: params?.endDate,
      search: params?.search,
    }),
    transform: transformApiToFrontend,
    errorMessage: '결제 내역을 불러오는데 실패했습니다.',
  });
}

// ===== 결제 명세서 조회 =====
export async function getPaymentStatement(id: string): Promise<ActionResult<StatementData>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/payments/${id}/statement`),
    transform: (data: PaymentStatementApiData): StatementData => ({
      statementNo: data.statement_no,
      issuedAt: data.issued_at,
      payment: {
        id: data.payment.id, amount: data.payment.amount, formattedAmount: data.payment.formatted_amount,
        paymentMethod: data.payment.payment_method, paymentMethodLabel: data.payment.payment_method_label,
        transactionId: data.payment.transaction_id, status: data.payment.status, statusLabel: data.payment.status_label,
        paidAt: data.payment.paid_at, memo: data.payment.memo,
      },
      subscription: {
        id: data.subscription.id, startedAt: data.subscription.started_at, endedAt: data.subscription.ended_at,
        status: data.subscription.status, statusLabel: data.subscription.status_label,
      },
      plan: data.plan ? {
        id: data.plan.id, name: data.plan.name, code: data.plan.code, price: data.plan.price,
        billingCycle: data.plan.billing_cycle, billingCycleLabel: data.plan.billing_cycle_label,
      } : null,
      customer: {
        tenantId: data.customer.tenant_id, companyName: data.customer.company_name,
        businessNumber: data.customer.business_number, representative: data.customer.representative,
        address: data.customer.address, email: data.customer.email, phone: data.customer.phone,
      },
      items: data.items,
      subtotal: data.subtotal,
      tax: data.tax,
      total: data.total,
    }),
    errorMessage: '명세서를 불러오는데 실패했습니다.',
  });
}
