/**
 * 매출 관리 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/sales - 목록 조회
 * - GET /api/v1/sales/{id} - 상세 조회
 * - POST /api/v1/sales - 등록
 * - PUT /api/v1/sales/{id} - 수정
 * - DELETE /api/v1/sales/{id} - 삭제
 * - PUT /api/v1/sales/{id}/confirm - 확정
 * - GET /api/v1/sales/summary - 요약 통계
 */

'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
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 { SalesRecord, SaleApiData } from './types';
import { transformApiToFrontend, transformFrontendToApi } from './types';

// ===== 매출 목록 조회 =====
export async function getSales(params?: {
  page?: number; perPage?: number; startDate?: string; endDate?: string;
  clientId?: string; status?: string; search?: string;
}) {
  return executePaginatedAction<SaleApiData, SalesRecord>({
    url: buildApiUrl('/api/v1/sales', {
      page: params?.page,
      per_page: params?.perPage,
      start_date: params?.startDate,
      end_date: params?.endDate,
      client_id: params?.clientId,
      status: params?.status && params.status !== 'all' ? params.status : undefined,
      search: params?.search,
    }),
    transform: transformApiToFrontend,
    errorMessage: '매출 목록 조회에 실패했습니다.',
  });
}

// ===== 매출 상세 조회 =====
export async function getSaleById(id: string): Promise<ActionResult<SalesRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/sales/${id}`),
    transform: (data: SaleApiData) => transformApiToFrontend(data),
    errorMessage: '매출 조회에 실패했습니다.',
  });
}

// ===== 매출 등록 =====
export async function createSale(data: Partial<SalesRecord>): Promise<ActionResult<SalesRecord>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/sales'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (data: SaleApiData) => transformApiToFrontend(data),
    errorMessage: '매출 등록에 실패했습니다.',
  });
}

// ===== 매출 수정 =====
export async function updateSale(id: string, data: Partial<SalesRecord>): Promise<ActionResult<SalesRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/sales/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (data: SaleApiData) => transformApiToFrontend(data),
    errorMessage: '매출 수정에 실패했습니다.',
  });
}

// ===== 세금계산서/거래명세서 발행 상태 토글 =====
export async function toggleSaleIssuance(
  id: string, field: 'taxInvoiceIssued' | 'transactionStatementIssued', value: boolean
): Promise<ActionResult<SalesRecord>> {
  const updateData: Partial<SalesRecord> =
    field === 'taxInvoiceIssued' ? { taxInvoiceIssued: value } : { transactionStatementIssued: value };
  try {
    return await updateSale(id, updateData);
  } catch (error) {
    if (isNextRedirectError(error)) {
      return { success: false, error: '세션이 만료되었습니다. 다시 로그인해주세요.' };
    }
    throw error;
  }
}

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

// ===== 매출 확정 =====
export async function confirmSale(id: string): Promise<ActionResult<SalesRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/sales/${id}/confirm`),
    method: 'PUT',
    transform: (data: SaleApiData) => transformApiToFrontend(data),
    errorMessage: '매출 확정에 실패했습니다.',
  });
}

// ===== 매출 요약 통계 =====
interface SalesSummaryApi { total_amount: string; total_count: number; confirmed_amount: string; confirmed_count: number; draft_amount: string; draft_count: number }

export async function getSalesSummary(params?: {
  startDate?: string; endDate?: string;
}): Promise<ActionResult<{
  totalAmount: number; totalCount: number; confirmedAmount: number; confirmedCount: number; draftAmount: number; draftCount: number;
}>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/sales/summary', {
      start_date: params?.startDate,
      end_date: params?.endDate,
    }),
    transform: (data: SalesSummaryApi) => ({
      totalAmount: parseFloat(data.total_amount) || 0, totalCount: data.total_count || 0,
      confirmedAmount: parseFloat(data.confirmed_amount) || 0, confirmedCount: data.confirmed_count || 0,
      draftAmount: parseFloat(data.draft_amount) || 0, draftCount: data.draft_count || 0,
    }),
    errorMessage: '매출 요약 조회에 실패했습니다.',
  });
}

// ===== 계정과목 일괄 수정 =====
export async function bulkUpdateSalesAccountCode(
  ids: number[], accountCode: string
): Promise<{ success: boolean; updatedCount?: number; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/sales/bulk-update-account'),
    method: 'PUT',
    body: { ids, account_code: accountCode },
    transform: (data: { updated_count?: number }) => ({ updatedCount: data?.updated_count || 0 }),
    errorMessage: '계정과목 수정에 실패했습니다.',
  });
  return { success: result.success, updatedCount: result.data?.updatedCount, error: result.error };
}
