'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { cookies } from 'next/headers';
import type { VendorReceivables, CategoryType, ReceivablesListResponse, MemoUpdateRequest } from './types';

// ===== API 응답 타입 =====
interface CategoryAmountApi {
  category: CategoryType;
  amounts: { values: number[]; total: number };
}

interface VendorReceivablesApi {
  id: string;
  vendor_id: number;
  vendor_name: string;
  is_overdue: boolean;
  memo: string;
  carry_forward_balance: number;
  month_labels: string[];
  categories: CategoryAmountApi[];
}

interface ReceivablesListApiResponse {
  month_labels: string[];
  items: VendorReceivablesApi[];
}

interface ReceivablesSummaryApi {
  total_carry_forward: number;
  total_sales: number;
  total_deposits: number;
  total_bills: number;
  total_receivables: number;
  vendor_count: number;
  overdue_vendor_count: number;
}

// ===== API → Frontend 변환 =====
function transformItem(item: VendorReceivablesApi): VendorReceivables {
  return {
    id: item.id,
    vendorName: item.vendor_name,
    isOverdue: item.is_overdue,
    memo: item.memo || '',
    carryForwardBalance: item.carry_forward_balance || 0,
    monthLabels: item.month_labels || [],
    categories: item.categories.map(cat => ({
      category: cat.category,
      amounts: { values: cat.amounts.values, total: cat.amounts.total },
    })),
  };
}

// ===== 채권 현황 목록 조회 =====
export async function getReceivablesList(params?: {
  year?: number; search?: string; hasReceivable?: boolean;
}): Promise<{ success: boolean; data: ReceivablesListResponse; error?: string }> {
  const yearValue = params?.year;
  const DEFAULT_DATA: ReceivablesListResponse = { monthLabels: [], items: [] };
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/receivables', {
      recent_year: typeof yearValue === 'number' && yearValue === 0 ? 'true' : undefined,
      year: typeof yearValue === 'number' && yearValue !== 0 ? yearValue : undefined,
      search: params?.search,
      has_receivable: params?.hasReceivable !== undefined ? String(params.hasReceivable) : undefined,
    }),
    transform: (data: ReceivablesListApiResponse) => ({
      monthLabels: data.month_labels || [],
      items: (data.items || []).map(transformItem),
    }),
    errorMessage: '채권 현황 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data || DEFAULT_DATA, error: result.error };
}

// ===== 채권 현황 요약 통계 =====
export async function getReceivablesSummary(params?: {
  year?: number;
}): Promise<ActionResult<{
  totalCarryForward: number; totalSales: number; totalDeposits: number; totalBills: number;
  totalReceivables: number; vendorCount: number; overdueVendorCount: number;
}>> {
  const yearValue = params?.year;
  return executeServerAction({
    url: buildApiUrl('/api/v1/receivables/summary', {
      recent_year: typeof yearValue === 'number' && yearValue === 0 ? 'true' : undefined,
      year: typeof yearValue === 'number' && yearValue !== 0 ? yearValue : undefined,
    }),
    transform: (data: ReceivablesSummaryApi) => ({
      totalCarryForward: data.total_carry_forward,
      totalSales: data.total_sales,
      totalDeposits: data.total_deposits,
      totalBills: data.total_bills,
      totalReceivables: data.total_receivables,
      vendorCount: data.vendor_count,
      overdueVendorCount: data.overdue_vendor_count,
    }),
    errorMessage: '요약 조회에 실패했습니다.',
  });
}

// ===== 연체 상태 일괄 업데이트 =====
export async function updateOverdueStatus(
  updates: Array<{ id: string; isOverdue: boolean }>
): Promise<{ success: boolean; updatedCount?: number; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/receivables/overdue-status'),
    method: 'PUT',
    body: { updates: updates.map(item => ({ id: parseInt(item.id, 10), is_overdue: item.isOverdue })) },
    transform: (data: { updated_count?: number }) => ({ updatedCount: data?.updated_count || updates.length }),
    errorMessage: '연체 상태 업데이트에 실패했습니다.',
  });
  return { success: result.success, updatedCount: result.data?.updatedCount, error: result.error };
}

// ===== 메모 일괄 업데이트 =====
export async function updateMemos(
  memos: MemoUpdateRequest[]
): Promise<{ success: boolean; updatedCount?: number; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/receivables/memos'),
    method: 'PUT',
    body: { memos: memos.map(item => ({ id: parseInt(item.id, 10), memo: item.memo })) },
    transform: (data: { updated_count?: number }) => ({ updatedCount: data?.updated_count || memos.length }),
    errorMessage: '메모 업데이트에 실패했습니다.',
  });
  return { success: result.success, updatedCount: result.data?.updatedCount, error: result.error };
}

// ===== 엑셀 다운로드 =====
export async function exportReceivablesExcel(params?: {
  year?: number;
  search?: string;
}): Promise<{
  success: boolean;
  data?: Blob;
  filename?: string;
  error?: string;
}> {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('access_token')?.value;

    const headers: HeadersInit = {
      'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Authorization': token ? `Bearer ${token}` : '',
      'X-API-KEY': process.env.API_KEY || '',
    };

    // year=0은 "최근 1년" 옵션 - recent_year 파라미터 사용
    const yearValue = params?.year;
    const url = buildApiUrl('/api/v1/receivables/export', {
      recent_year: typeof yearValue === 'number' && yearValue === 0 ? 'true' : undefined,
      year: typeof yearValue === 'number' && yearValue !== 0 ? yearValue : undefined,
      search: params?.search,
    });

    const response = await fetch(url, {
      method: 'GET',
      headers,
    });

    if (!response.ok) {
      console.warn('[ReceivablesActions] GET export error:', response.status);
      return {
        success: false,
        error: `API 오류: ${response.status}`,
      };
    }

    const blob = await response.blob();
    const contentDisposition = response.headers.get('Content-Disposition');
    const filename = contentDisposition?.match(/filename="?(.+)"?/)?.[1] || `채권현황_${params?.year || new Date().getFullYear()}.xlsx`;

    return {
      success: true,
      data: blob,
      filename,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[ReceivablesActions] exportReceivablesExcel error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}