'use server';

import { getTodayString } from '@/lib/utils/date';
import type { PricingTable, PricingTableFormData, TradeGrade } from './types';

// ============================================================================
// 목데이터
// ============================================================================

const MOCK_PRICING_TABLES: PricingTable[] = [
  {
    id: '1',
    pricingCode: '123123',
    itemCode: '123123',
    itemType: '반제품',
    itemName: '품목명A',
    specification: 'ST',
    unit: 'EA',
    purchasePrice: 10000,
    processingCost: 5000,
    status: '사용',
    author: '홍길동',
    changedDate: '2026-01-15',
    gradePricings: [
      { id: 'gp-1-1', grade: 'A등급', marginRate: 50.0, sellingPrice: 20000, note: '' },
      { id: 'gp-1-2', grade: 'B등급', marginRate: 50.0, sellingPrice: 20000, note: '' },
      { id: 'gp-1-3', grade: 'C등급', marginRate: 50.0, sellingPrice: 20000, note: '' },
      { id: 'gp-1-4', grade: 'D등급', marginRate: 50.0, sellingPrice: 20000, note: '' },
    ],
  },
  {
    id: '2',
    pricingCode: '123124',
    itemCode: '123124',
    itemType: '완제품',
    itemName: '품목명B',
    specification: '규격B',
    unit: 'SET',
    purchasePrice: 8000,
    processingCost: 3000,
    status: '사용',
    author: '김철수',
    changedDate: '2026-01-20',
    gradePricings: [
      { id: 'gp-2-1', grade: 'A등급', marginRate: 40.0, sellingPrice: 14000, note: '' },
      { id: 'gp-2-2', grade: 'B등급', marginRate: 35.0, sellingPrice: 13000, note: '' },
    ],
  },
  {
    id: '3',
    pricingCode: '123125',
    itemCode: '123125',
    itemType: '반제품',
    itemName: '품목명C',
    specification: 'ST',
    unit: 'EA',
    purchasePrice: 15000,
    processingCost: 5000,
    status: '미사용',
    author: '이영희',
    changedDate: '2026-01-10',
    gradePricings: [
      { id: 'gp-3-1', grade: 'A등급', marginRate: 50.0, sellingPrice: 27000, note: '' },
      { id: 'gp-3-2', grade: 'B등급', marginRate: 45.0, sellingPrice: 26000, note: '' },
      { id: 'gp-3-3', grade: 'C등급', marginRate: 40.0, sellingPrice: 26000, note: '' },
    ],
  },
  {
    id: '4',
    pricingCode: '123126',
    itemCode: '123126',
    itemType: '원자재',
    itemName: '품목명D',
    specification: 'AL',
    unit: 'KG',
    purchasePrice: 5000,
    processingCost: 2000,
    status: '사용',
    author: '박민수',
    changedDate: '2026-02-01',
    gradePricings: [
      { id: 'gp-4-1', grade: 'A등급', marginRate: 60.0, sellingPrice: 10000, note: '' },
      { id: 'gp-4-2', grade: 'B등급', marginRate: 55.0, sellingPrice: 9000, note: '' },
    ],
  },
  {
    id: '5',
    pricingCode: '123127',
    itemCode: '123127',
    itemType: '완제품',
    itemName: '품목명E',
    specification: '규격E',
    unit: 'SET',
    purchasePrice: 20000,
    processingCost: 8000,
    status: '사용',
    author: '홍길동',
    changedDate: '2026-01-25',
    gradePricings: [
      { id: 'gp-5-1', grade: 'A등급', marginRate: 50.0, sellingPrice: 38000, note: '' },
      { id: 'gp-5-2', grade: 'B등급', marginRate: 45.0, sellingPrice: 37000, note: '' },
      { id: 'gp-5-3', grade: 'C등급', marginRate: 40.0, sellingPrice: 36000, note: '' },
      { id: 'gp-5-4', grade: 'D등급', marginRate: 35.0, sellingPrice: 35000, note: '' },
    ],
  },
  {
    id: '6',
    pricingCode: '123128',
    itemCode: '123128',
    itemType: '반제품',
    itemName: '품목명F',
    specification: 'ST',
    unit: 'EA',
    purchasePrice: 12000,
    processingCost: 4000,
    status: '사용',
    author: '김철수',
    changedDate: '2026-01-18',
    gradePricings: [
      { id: 'gp-6-1', grade: 'A등급', marginRate: 50.0, sellingPrice: 22000, note: '' },
    ],
  },
  {
    id: '7',
    pricingCode: '123129',
    itemCode: '123129',
    itemType: '원자재',
    itemName: '품목명G',
    specification: 'SUS',
    unit: 'KG',
    purchasePrice: 7000,
    processingCost: 3000,
    status: '사용',
    author: '이영희',
    changedDate: '2026-01-22',
    gradePricings: [
      { id: 'gp-7-1', grade: 'A등급', marginRate: 45.0, sellingPrice: 13000, note: '' },
      { id: 'gp-7-2', grade: 'B등급', marginRate: 40.0, sellingPrice: 12000, note: '' },
    ],
  },
];

// ============================================================================
// API 함수 (목데이터 기반)
// ============================================================================

/**
 * 단가표 목록 조회
 */
export async function getPricingTableList(params?: {
  page?: number;
  size?: number;
  q?: string;
  status?: string;
  grade?: TradeGrade;
}): Promise<{
  success: boolean;
  data?: { items: PricingTable[]; total: number };
  error?: string;
}> {
  let items = [...MOCK_PRICING_TABLES];

  // 상태 필터
  if (params?.status) {
    items = items.filter((item) => item.status === params.status);
  }

  // 거래등급 필터 (해당 등급의 gradePricing이 있는 항목만)
  if (params?.grade) {
    items = items.filter((item) =>
      item.gradePricings.some((gp) => gp.grade === params.grade)
    );
  }

  // 검색
  if (params?.q) {
    const q = params.q.toLowerCase();
    items = items.filter(
      (item) =>
        item.pricingCode.toLowerCase().includes(q) ||
        item.itemCode.toLowerCase().includes(q) ||
        item.itemName.toLowerCase().includes(q) ||
        item.itemType.toLowerCase().includes(q)
    );
  }

  return {
    success: true,
    data: { items, total: items.length },
  };
}

/**
 * 단가표 통계
 */
export async function getPricingTableStats(): Promise<{
  success: boolean;
  data?: { total: number; active: number; inactive: number };
  error?: string;
}> {
  const total = MOCK_PRICING_TABLES.length;
  const active = MOCK_PRICING_TABLES.filter((p) => p.status === '사용').length;
  const inactive = total - active;
  return { success: true, data: { total, active, inactive } };
}

/**
 * 단가표 상세 조회
 */
export async function getPricingTableById(id: string): Promise<{
  success: boolean;
  data?: PricingTable;
  error?: string;
}> {
  const item = MOCK_PRICING_TABLES.find((p) => p.id === id);
  if (!item) {
    return { success: false, error: '단가표를 찾을 수 없습니다.' };
  }
  return { success: true, data: item };
}

/**
 * 단가표 생성
 */
export async function createPricingTable(data: PricingTableFormData): Promise<{
  success: boolean;
  data?: PricingTable;
  error?: string;
}> {
  const newItem: PricingTable = {
    id: String(Date.now()),
    pricingCode: `PT-${Date.now()}`,
    itemCode: data.itemCode,
    itemType: data.itemType,
    itemName: data.itemName,
    specification: data.specification,
    unit: data.unit,
    purchasePrice: data.purchasePrice,
    processingCost: data.processingCost,
    status: data.status,
    author: '현재사용자',
    changedDate: getTodayString(),
    gradePricings: data.gradePricings,
  };
  return { success: true, data: newItem };
}

/**
 * 단가표 수정
 */
export async function updatePricingTable(
  id: string,
  data: PricingTableFormData
): Promise<{
  success: boolean;
  data?: PricingTable;
  error?: string;
}> {
  const existing = MOCK_PRICING_TABLES.find((p) => p.id === id);
  if (!existing) {
    return { success: false, error: '단가표를 찾을 수 없습니다.' };
  }
  const updated: PricingTable = {
    ...existing,
    ...data,
    changedDate: getTodayString(),
  };
  return { success: true, data: updated };
}

/**
 * 단가표 삭제
 */
export async function deletePricingTable(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  const exists = MOCK_PRICING_TABLES.find((p) => p.id === id);
  if (!exists) {
    return { success: false, error: '단가표를 찾을 수 없습니다.' };
  }
  return { success: true };
}

/**
 * 단가표 일괄 삭제
 */
export async function deletePricingTables(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  return { success: true, deletedCount: ids.length };
}

