'use server';

import type {
  Bidding,
  BiddingStats,
  BiddingListResponse,
  BiddingFilter,
  BiddingDetail,
  BiddingDetailFormData,
  ExpenseItem,
  EstimateDetailItem,
} from './types';
import { apiClient } from '@/lib/api';

/**
 * 건설 프로젝트 - 입찰관리 Server Actions
 * biddings API 사용
 */

// ========================================
// API 응답 타입 (Biddings API)
// ========================================

interface ApiBidding {
  id: number;
  bidding_code: string;
  quote_id: number | null;
  client_id: number | null;
  client_name: string | null;
  project_name: string | null;
  bidding_date: string | null;
  bid_date: string | null;
  submission_date: string | null;
  confirm_date: string | null;
  total_count: number;
  bidding_amount: number | string;
  status: string;
  bidder_id: number | null;
  bidder_name: string | null;
  construction_start_date: string | null;
  construction_end_date: string | null;
  vat_type: string;
  remarks: string | null;
  expense_items: ExpenseItem[] | null;
  estimate_detail_items: EstimateDetailItem[] | null;
  created_at: string;
  updated_at: string;
  created_by: number | null;
  // 연관 데이터
  quote?: {
    id: number;
    quote_number: string;
  };
}

// ========================================
// 변환 함수
// ========================================

function transformBidding(api: ApiBidding): Bidding {
  return {
    id: String(api.id),
    biddingCode: api.bidding_code,
    partnerId: api.client_id ? String(api.client_id) : '',
    partnerName: api.client_name || '',
    projectName: api.project_name || '',
    biddingDate: api.bidding_date || '',
    totalCount: api.total_count,
    biddingAmount: typeof api.bidding_amount === 'string' ? parseFloat(api.bidding_amount) : api.bidding_amount,
    bidDate: api.bid_date || '',
    submissionDate: api.submission_date || null,
    confirmDate: api.confirm_date || null,
    status: api.status as Bidding['status'],
    bidderId: api.bidder_id ? String(api.bidder_id) : '',
    bidderName: api.bidder_name || '',
    remarks: api.remarks || '',
    createdAt: api.created_at,
    updatedAt: api.updated_at,
    createdBy: api.created_by ? String(api.created_by) : '',
    estimateId: api.quote_id ? String(api.quote_id) : '',
    estimateCode: api.quote?.quote_number || '',
  };
}

function transformBiddingDetail(api: ApiBidding): BiddingDetail {
  return {
    ...transformBidding(api),
    constructionStartDate: api.construction_start_date || '',
    constructionEndDate: api.construction_end_date || '',
    vatType: (api.vat_type || 'excluded') as 'included' | 'excluded',
    expenseItems: api.expense_items || [],
    estimateDetailItems: api.estimate_detail_items || [],
  };
}

// ========================================
// API 함수
// ========================================

// 입찰 목록 조회
export async function getBiddingList(filter?: BiddingFilter): Promise<{
  success: boolean;
  data?: BiddingListResponse;
  error?: string;
}> {

  try {
    const queryParams: Record<string, string> = {};

    // 검색 (API는 'search' 파라미터 사용)
    if (filter?.search) queryParams.search = filter.search;

    // 필터
    if (filter?.status && filter.status !== 'all') {
      queryParams.status = filter.status;
    }
    if (filter?.partnerId && filter.partnerId !== 'all') {
      queryParams.client_id = filter.partnerId;
    }
    if (filter?.bidderId && filter.bidderId !== 'all') {
      queryParams.bidder_id = filter.bidderId;
    }

    // 날짜 범위 (API는 'from_date', 'to_date' 파라미터 사용)
    if (filter?.startDate) queryParams.from_date = filter.startDate;
    if (filter?.endDate) queryParams.to_date = filter.endDate;

    // 정렬 (API는 'sort_dir' 파라미터 사용)
    if (filter?.sortBy) {
      const sortMap: Record<string, { sort_by: string; sort_dir: string }> = {
        biddingDateDesc: { sort_by: 'bidding_date', sort_dir: 'desc' },
        biddingDateAsc: { sort_by: 'bidding_date', sort_dir: 'asc' },
        submissionDateDesc: { sort_by: 'submission_date', sort_dir: 'desc' },
        confirmDateDesc: { sort_by: 'confirm_date', sort_dir: 'desc' },
        partnerNameAsc: { sort_by: 'client_name', sort_dir: 'asc' },
        partnerNameDesc: { sort_by: 'client_name', sort_dir: 'desc' },
        projectNameAsc: { sort_by: 'project_name', sort_dir: 'asc' },
        projectNameDesc: { sort_by: 'project_name', sort_dir: 'desc' },
      };
      const sortConfig = sortMap[filter.sortBy];
      if (sortConfig) {
        queryParams.sort_by = sortConfig.sort_by;
        queryParams.sort_dir = sortConfig.sort_dir;
      }
    }

    // 페이지네이션 (API는 'per_page' 파라미터 사용)
    if (filter?.page) queryParams.page = String(filter.page);
    if (filter?.size) queryParams.per_page = String(filter.size);


    const response = await apiClient.get<{
      success: boolean;
      data: {
        data: ApiBidding[];
        current_page: number;
        per_page: number;
        total: number;
        last_page: number;
      };
    }>('/biddings', { params: queryParams });


    const paginatedData = response.data;
    const items = (paginatedData.data || []).map(transformBidding);


    return {
      success: true,
      data: {
        items,
        total: paginatedData.total || 0,
        page: paginatedData.current_page || 1,
        size: paginatedData.per_page || 20,
        totalPages: paginatedData.last_page || 1,
      },
    };
  } catch (error) {
    console.error('❌ [getBiddingList] 에러:', error);
    return { success: false, error: '입찰 목록을 불러오는데 실패했습니다.' };
  }
}

// 입찰 통계 조회
export async function getBiddingStats(): Promise<{
  success: boolean;
  data?: BiddingStats;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: {
        total: number;
        waiting: number;
        awarded: number;
      };
    }>('/biddings/stats');

    return {
      success: true,
      data: {
        total: response.data.total,
        waiting: response.data.waiting,
        awarded: response.data.awarded,
      },
    };
  } catch (error) {
    console.error('getBiddingStats error:', error);
    return { success: false, error: '통계를 불러오는데 실패했습니다.' };
  }
}

// 입찰 단건 조회
export async function getBidding(id: string): Promise<{
  success: boolean;
  data?: Bidding;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{ success: boolean; data: ApiBidding }>(`/biddings/${id}`);
    return { success: true, data: transformBidding(response.data) };
  } catch (error) {
    console.error('getBidding error:', error);
    return { success: false, error: '입찰 정보를 불러오는데 실패했습니다.' };
  }
}

// 입찰 삭제
export async function deleteBidding(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await apiClient.delete(`/biddings/${id}`);
    return { success: true };
  } catch (error) {
    console.error('deleteBidding error:', error);
    return { success: false, error: '입찰 삭제에 실패했습니다.' };
  }
}

// 입찰 일괄 삭제
export async function deleteBiddings(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    await apiClient.delete('/biddings/bulk', {
      data: { ids: ids.map((id) => parseInt(id, 10)) },
    });
    return { success: true, deletedCount: ids.length };
  } catch (error) {
    console.error('deleteBiddings error:', error);
    return { success: false, error: '일괄 삭제에 실패했습니다.' };
  }
}

// 입찰 상세 조회
export async function getBiddingDetail(id: string): Promise<{
  success: boolean;
  data?: BiddingDetail;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{ success: boolean; data: ApiBidding }>(`/biddings/${id}`);
    return { success: true, data: transformBiddingDetail(response.data) };
  } catch (error) {
    console.error('getBiddingDetail error:', error);
    return { success: false, error: '입찰 상세를 불러오는데 실패했습니다.' };
  }
}

// 입찰 수정
export async function updateBidding(
  id: string,
  data: Partial<BiddingDetailFormData>
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    // camelCase → snake_case 변환
    const payload: Record<string, unknown> = {};

    if (data.projectName !== undefined) payload.project_name = data.projectName;
    if (data.biddingDate !== undefined) payload.bidding_date = data.biddingDate;
    if (data.submissionDate !== undefined) payload.submission_date = data.submissionDate;
    if (data.confirmDate !== undefined) payload.confirm_date = data.confirmDate;
    if (data.totalCount !== undefined) payload.total_count = data.totalCount;
    if (data.biddingAmount !== undefined) payload.bidding_amount = data.biddingAmount;
    if (data.status !== undefined) payload.status = data.status;
    if (data.bidderId !== undefined) payload.bidder_id = data.bidderId ? parseInt(data.bidderId, 10) : null;
    if (data.bidderName !== undefined) payload.bidder_name = data.bidderName;
    if (data.constructionStartDate !== undefined) payload.construction_start_date = data.constructionStartDate;
    if (data.constructionEndDate !== undefined) payload.construction_end_date = data.constructionEndDate;
    if (data.vatType !== undefined) payload.vat_type = data.vatType;
    if (data.remarks !== undefined) payload.remarks = data.remarks;

    await apiClient.put(`/biddings/${id}`, payload);
    return { success: true };
  } catch (error) {
    console.error('updateBidding error:', error);
    return { success: false, error: '입찰 수정에 실패했습니다.' };
  }
}

// 입찰 상태 변경
export async function updateBiddingStatus(
  id: string,
  status: Bidding['status']
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await apiClient.patch(`/biddings/${id}/status`, { status });
    return { success: true };
  } catch (error) {
    console.error('updateBiddingStatus error:', error);
    return { success: false, error: '상태 변경에 실패했습니다.' };
  }
}

// ========================================
// 입찰 생성 (견적에서 전환)
// ========================================

// 입찰 생성 요청 데이터
export interface CreateBiddingData {
  quoteId?: number; // 견적 ID (연결)
  clientId?: number;
  clientName?: string;
  projectName: string;
  biddingDate?: string;
  bidDate?: string;
  submissionDate?: string;
  confirmDate?: string;
  totalCount?: number;
  biddingAmount?: number;
  status?: Bidding['status'];
  bidderId?: number;
  bidderName?: string;
  constructionStartDate?: string;
  constructionEndDate?: string;
  vatType?: 'included' | 'excluded';
  remarks?: string;
  expenseItems?: ExpenseItem[];
  estimateDetailItems?: EstimateDetailItem[];
}

// 입찰 생성
export async function createBidding(data: CreateBiddingData): Promise<{
  success: boolean;
  data?: Bidding;
  error?: string;
}> {
  try {
    // camelCase → snake_case 변환
    const payload: Record<string, unknown> = {
      project_name: data.projectName,
    };

    if (data.quoteId !== undefined) payload.quote_id = data.quoteId;
    if (data.clientId !== undefined) payload.client_id = data.clientId;
    if (data.clientName !== undefined) payload.client_name = data.clientName;
    if (data.biddingDate !== undefined) payload.bidding_date = data.biddingDate;
    if (data.bidDate !== undefined) payload.bid_date = data.bidDate;
    if (data.submissionDate !== undefined) payload.submission_date = data.submissionDate;
    if (data.confirmDate !== undefined) payload.confirm_date = data.confirmDate;
    if (data.totalCount !== undefined) payload.total_count = data.totalCount;
    if (data.biddingAmount !== undefined) payload.bidding_amount = data.biddingAmount;
    if (data.status !== undefined) payload.status = data.status;
    if (data.bidderId !== undefined) payload.bidder_id = data.bidderId;
    if (data.bidderName !== undefined) payload.bidder_name = data.bidderName;
    if (data.constructionStartDate !== undefined) payload.construction_start_date = data.constructionStartDate;
    if (data.constructionEndDate !== undefined) payload.construction_end_date = data.constructionEndDate;
    if (data.vatType !== undefined) payload.vat_type = data.vatType;
    if (data.remarks !== undefined) payload.remarks = data.remarks;
    if (data.expenseItems !== undefined) payload.expense_items = data.expenseItems;
    if (data.estimateDetailItems !== undefined) payload.estimate_detail_items = data.estimateDetailItems;

    const response = await apiClient.post<{ success: boolean; data: ApiBidding }>('/biddings', payload);
    return { success: true, data: transformBidding(response.data) };
  } catch (error) {
    console.error('createBidding error:', error);
    return { success: false, error: '입찰 생성에 실패했습니다.' };
  }
}

// 견적에서 입찰로 전환 (헬퍼 함수)
export async function createBiddingFromEstimate(estimate: {
  id: string;
  partnerId?: string;
  partnerName?: string;
  projectName: string;
  estimateAmount?: number;
  itemCount?: number;
  bidDate?: string | null;
  bidInfo?: {
    projectName?: string;
    bidDate?: string;
    siteCount?: number;
    constructionStartDate?: string;
    constructionEndDate?: string;
    vatType?: string;
  };
  expenseItems?: ExpenseItem[];
  detailItems?: EstimateDetailItem[];
}): Promise<{
  success: boolean;
  data?: Bidding;
  error?: string;
}> {
  const biddingData: CreateBiddingData = {
    quoteId: parseInt(estimate.id, 10),
    clientId: estimate.partnerId ? parseInt(estimate.partnerId, 10) : undefined,
    clientName: estimate.partnerName,
    projectName: estimate.bidInfo?.projectName || estimate.projectName,
    bidDate: estimate.bidInfo?.bidDate || estimate.bidDate || undefined,
    totalCount: estimate.bidInfo?.siteCount || estimate.itemCount || 0,
    biddingAmount: estimate.estimateAmount || 0,
    constructionStartDate: estimate.bidInfo?.constructionStartDate,
    constructionEndDate: estimate.bidInfo?.constructionEndDate,
    vatType: (estimate.bidInfo?.vatType as 'included' | 'excluded') || 'excluded',
    expenseItems: estimate.expenseItems,
    estimateDetailItems: estimate.detailItems,
  };

  return createBidding(biddingData);
}