'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { cookies } from 'next/headers';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { VendorReceivables, CategoryType, MonthlyAmount, 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;
}> {
  try {
    const searchParams = new URLSearchParams();

    // year=0은 "최근 1년" 옵션 - recent_year 파라미터 사용
    // 명시적으로 year가 숫자이고 0인지 확인 (undefined와 구분)
    const yearValue = params?.year;
    if (typeof yearValue === 'number') {
      if (yearValue === 0) {
        searchParams.set('recent_year', 'true');
      } else {
        searchParams.set('year', String(yearValue));
      }
    }
    if (params?.search) searchParams.set('search', params.search);
    if (params?.hasReceivable !== undefined) {
      searchParams.set('has_receivable', params.hasReceivable ? 'true' : 'false');
    }

    const queryString = searchParams.toString();
    console.log('[ReceivablesActions] getReceivablesList - year:', yearValue, 'queryString:', queryString);
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivables${queryString ? `?${queryString}` : ''}`;

    const { response, error } = await serverFetch(url, { method: 'GET' });

    if (error) {
      return { success: false, data: { monthLabels: [], items: [] }, error: error.message };
    }

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

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        data: { monthLabels: [], items: [] },
        error: result.message || '채권 현황 조회에 실패했습니다.',
      };
    }

    const apiData: ReceivablesListApiResponse = result.data;
    const items = (apiData.items || []).map(transformItem);

    return {
      success: true,
      data: {
        monthLabels: apiData.month_labels || [],
        items,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[ReceivablesActions] getReceivablesList error:', error);
    return {
      success: false,
      data: { monthLabels: [], items: [] },
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 채권 현황 요약 통계 =====
export async function getReceivablesSummary(params?: {
  year?: number;
}): Promise<{
  success: boolean;
  data?: {
    totalCarryForward: number;
    totalSales: number;
    totalDeposits: number;
    totalBills: number;
    totalReceivables: number;
    vendorCount: number;
    overdueVendorCount: number;
  };
  error?: string;
}> {
  try {
    const searchParams = new URLSearchParams();

    // year=0은 "최근 1년" 옵션 - recent_year 파라미터 사용
    const yearValue = params?.year;
    if (typeof yearValue === 'number') {
      if (yearValue === 0) {
        searchParams.set('recent_year', 'true');
      } else {
        searchParams.set('year', String(yearValue));
      }
    }

    const queryString = searchParams.toString();
    console.log('[ReceivablesActions] getReceivablesSummary - year:', yearValue, 'queryString:', queryString);
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivables/summary${queryString ? `?${queryString}` : ''}`;

    const { response, error } = await serverFetch(url, { method: 'GET' });

    if (error) {
      return { success: false, error: error.message };
    }

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

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        error: result.message || '요약 조회에 실패했습니다.',
      };
    }

    const apiSummary: ReceivablesSummaryApi = result.data;

    return {
      success: true,
      data: {
        totalCarryForward: apiSummary.total_carry_forward,
        totalSales: apiSummary.total_sales,
        totalDeposits: apiSummary.total_deposits,
        totalBills: apiSummary.total_bills,
        totalReceivables: apiSummary.total_receivables,
        vendorCount: apiSummary.vendor_count,
        overdueVendorCount: apiSummary.overdue_vendor_count,
      },
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[ReceivablesActions] getReceivablesSummary error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 연체 상태 일괄 업데이트 =====
export async function updateOverdueStatus(
  updates: Array<{ id: string; isOverdue: boolean }>
): Promise<{
  success: boolean;
  updatedCount?: number;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivables/overdue-status`;

    const { response, error } = await serverFetch(url, {
      method: 'PUT',
      body: JSON.stringify({
        updates: updates.map(item => ({
          id: parseInt(item.id, 10),
          is_overdue: item.isOverdue,
        })),
      }),
    });

    if (error) {
      return { success: false, error: error.message };
    }

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

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        error: result.message || '연체 상태 업데이트에 실패했습니다.',
      };
    }

    return {
      success: true,
      updatedCount: result.data?.updated_count || updates.length,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[ReceivablesActions] updateOverdueStatus error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 메모 일괄 업데이트 =====
export async function updateMemos(
  memos: MemoUpdateRequest[]
): Promise<{
  success: boolean;
  updatedCount?: number;
  error?: string;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivables/memos`;

    const { response, error } = await serverFetch(url, {
      method: 'PUT',
      body: JSON.stringify({
        memos: memos.map(item => ({
          id: parseInt(item.id, 10),
          memo: item.memo,
        })),
      }),
    });

    if (error) {
      return { success: false, error: error.message };
    }

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

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        error: result.message || '메모 업데이트에 실패했습니다.',
      };
    }

    return {
      success: true,
      updatedCount: result.data?.updated_count || memos.length,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[ReceivablesActions] updateMemos error:', error);
    return {
      success: false,
      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 || '',
    };

    const searchParams = new URLSearchParams();
    // year=0은 "최근 1년" 옵션 - recent_year 파라미터 사용
    const yearValue = params?.year;
    if (typeof yearValue === 'number') {
      if (yearValue === 0) {
        searchParams.set('recent_year', 'true');
      } else {
        searchParams.set('year', String(yearValue));
      }
    }
    if (params?.search) searchParams.set('search', params.search);

    const queryString = searchParams.toString();
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivables/export${queryString ? `?${queryString}` : ''}`;

    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: '서버 오류가 발생했습니다.',
    };
  }
}