'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 { isNextRedirectError } from '@/lib/utils/redirect-error';
import { cookies } from 'next/headers';
import type { VendorLedgerItem, VendorLedgerDetail, VendorLedgerSummary, TransactionEntry } from './types';

// ===== API 응답 타입 =====
interface VendorLedgerApiItem {
  id: number;
  name: string;
  sales_payment_day: string | null;
  period_sales: number | string;
  period_collection: number | string;
  carryover_sales: number | string;
  carryover_deposits: number | string;
}

interface VendorLedgerApiSummary {
  carryover_balance: number;
  total_sales: number;
  total_collection: number;
  balance: number;
}

interface VendorLedgerApiClient {
  id: number;
  name: string;
  business_number: string | null;
  representative_name: string | null;
  phone: string | null;
  mobile: string | null;
  fax: string | null;
  email: string | null;
  address: string | null;
}

interface VendorLedgerApiTransaction {
  id: number;
  date: string;
  type: 'sales' | 'collection' | 'note';
  description: string;
  sales_amount: number;
  collection_amount: number;
  balance: number;
  reference_id: number;
  reference_type: 'sale' | 'deposit' | 'bill';
  has_action: boolean;
  is_highlighted: boolean;
  is_parenthesis?: boolean;
  note_info?: string | null;
}

interface VendorLedgerApiDetail {
  client: VendorLedgerApiClient;
  period: { start_date: string | null; end_date: string | null };
  carryover_balance: number;
  total_sales: number;
  total_collection: number;
  balance: number;
  transactions: VendorLedgerApiTransaction[];
}

// ===== API → Frontend 변환 =====
function transformListItem(item: VendorLedgerApiItem): VendorLedgerItem {
  const carryoverSales = typeof item.carryover_sales === 'string' ? parseFloat(item.carryover_sales) : item.carryover_sales;
  const carryoverDeposits = typeof item.carryover_deposits === 'string' ? parseFloat(item.carryover_deposits) : item.carryover_deposits;
  const periodSales = typeof item.period_sales === 'string' ? parseFloat(item.period_sales) : item.period_sales;
  const periodCollection = typeof item.period_collection === 'string' ? parseFloat(item.period_collection) : item.period_collection;
  const carryoverBalance = carryoverSales - carryoverDeposits;
  const balance = carryoverBalance + periodSales - periodCollection;

  return {
    id: String(item.id),
    vendorName: item.name,
    carryoverBalance,
    sales: periodSales,
    collection: periodCollection,
    balance,
    paymentDate: item.sales_payment_day || '',
  };
}

function transformTransaction(tx: VendorLedgerApiTransaction): TransactionEntry {
  let type: TransactionEntry['type'] = 'sales';
  if (tx.type === 'collection') type = 'sales';
  if (tx.type === 'note') type = 'note';
  if (tx.type === 'sales') type = 'sales';

  return {
    id: String(tx.id),
    date: tx.date,
    description: tx.description,
    salesAmount: tx.sales_amount,
    collectionAmount: tx.collection_amount,
    balance: tx.balance,
    type,
    isHighlighted: tx.is_highlighted,
    isParenthesis: tx.is_parenthesis || false,
    noteInfo: tx.note_info || undefined,
    hasAction: tx.has_action,
  };
}

function transformDetail(data: VendorLedgerApiDetail): VendorLedgerDetail {
  return {
    id: String(data.client.id),
    vendorName: data.client.name,
    businessNumber: data.client.business_number || '',
    representativeName: data.client.representative_name || '',
    phone: data.client.phone || '',
    mobile: data.client.mobile || '',
    fax: data.client.fax || '',
    email: data.client.email || '',
    address: data.client.address || '',
    periodStart: data.period.start_date || '',
    periodEnd: data.period.end_date || '',
    transactions: data.transactions.map(transformTransaction),
  };
}

// ===== 거래처원장 목록 조회 =====
export async function getVendorLedgerList(params?: {
  page?: number; perPage?: number; startDate?: string; endDate?: string;
  search?: string; sortBy?: string; sortDir?: 'asc' | 'desc';
}) {
  return executePaginatedAction<VendorLedgerApiItem, VendorLedgerItem>({
    url: buildApiUrl('/api/v1/vendor-ledger', {
      page: params?.page,
      per_page: params?.perPage,
      start_date: params?.startDate,
      end_date: params?.endDate,
      search: params?.search,
      sort_by: params?.sortBy,
      sort_dir: params?.sortDir,
    }),
    transform: transformListItem,
    errorMessage: '거래처원장 조회에 실패했습니다.',
  });
}

// ===== 거래처원장 요약 통계 조회 =====
export async function getVendorLedgerSummary(params?: {
  startDate?: string; endDate?: string;
}): Promise<ActionResult<VendorLedgerSummary>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/vendor-ledger/summary', {
      start_date: params?.startDate,
      end_date: params?.endDate,
    }),
    transform: (data: VendorLedgerApiSummary) => ({
      carryoverBalance: data.carryover_balance,
      totalSales: data.total_sales,
      totalCollection: data.total_collection,
      balance: data.balance,
    }),
    errorMessage: '요약 조회에 실패했습니다.',
  });
}

// ===== 거래처원장 상세 조회 =====
export async function getVendorLedgerDetail(clientId: string, params?: {
  startDate?: string; endDate?: string;
}): Promise<{ success: boolean; data?: VendorLedgerDetail; summary?: VendorLedgerSummary; error?: string }> {
  const result = await executeServerAction({
    url: buildApiUrl(`/api/v1/vendor-ledger/${clientId}`, {
      start_date: params?.startDate,
      end_date: params?.endDate,
    }),
    transform: (data: VendorLedgerApiDetail) => ({
      detail: transformDetail(data),
      summary: {
        carryoverBalance: data.carryover_balance,
        totalSales: data.total_sales,
        totalCollection: data.total_collection,
        balance: data.balance,
      } as VendorLedgerSummary,
    }),
    errorMessage: '거래처원장 상세 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data?.detail, summary: result.data?.summary, error: result.error };
}

// ===== 거래처원장 목록 엑셀 다운로드 =====
export async function exportVendorLedgerExcel(params?: {
  startDate?: string;
  endDate?: string;
  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 || '',
    };

    const url = buildApiUrl('/api/v1/vendor-ledger/export', {
      start_date: params?.startDate,
      end_date: params?.endDate,
      search: params?.search,
    });

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

    if (!response.ok) {
      console.warn('[VendorLedgerActions] 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?.startDate || 'all'}.xlsx`;

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

// ===== 거래처원장 상세 PDF 다운로드 =====
export async function exportVendorLedgerDetailPdf(clientId: string, params?: {
  startDate?: string;
  endDate?: 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/pdf',
      'Authorization': token ? `Bearer ${token}` : '',
      'X-API-KEY': process.env.API_KEY || '',
    };

    const url = buildApiUrl(`/api/v1/vendor-ledger/${clientId}/export-pdf`, {
      start_date: params?.startDate,
      end_date: params?.endDate,
    });

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

    if (!response.ok) {
      console.warn('[VendorLedgerActions] GET export-pdf 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] || `거래처원장_${clientId}.pdf`;

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