'use server';

import type { SiteBriefing, SiteBriefingStats, SiteBriefingFilter, SiteBriefingListResponse, SiteBriefingFormData } from './types';
import { apiClient } from '@/lib/api';

/**
 * 주일 기업 - 현장설명회 관리 Server Actions
 * 표준화된 apiClient 사용 버전
 */

// ========================================
// API 응답 타입
// ========================================

interface ApiSiteBriefing {
  id: number;
  briefing_code: string | null;
  title: string;
  description: string | null;
  partner_id: number | null;
  partner_name: string | null;
  briefing_date: string;
  briefing_time: string | null;
  briefing_type: string | null;
  location: string | null;
  address: string | null;
  status: string | null;
  bid_status: string | null;
  bid_date: string | null;
  attendees: Array<{ id: string; name: string }> | null; // 백엔드는 attendees (복수형), array 타입
  attendance_status: string | null;
  project_name: string | null;
  site_count: number | null;
  construction_start_date: string | null;
  construction_end_date: string | null;
  vat_type: string | null;
  work_report: string | null;
  attendee_count: number | null;
  created_at: string;
  updated_at: string;
  created_by: string | null;
}

interface ApiSiteBriefingStats {
  total: number;
  scheduled: number;
  ongoing: number;
  completed: number;
  cancelled: number;
}

// ========================================
// 타입 변환 함수
// ========================================

/**
 * API 응답 → SiteBriefing 타입 변환
 */
function transformSiteBriefing(apiData: ApiSiteBriefing): SiteBriefing {
  // attendees를 JSON 문자열로 변환 (types.ts의 parseAttendeeItems에서 파싱)
  const attendeeJson = apiData.attendees ? JSON.stringify(apiData.attendees) : '';

  return {
    id: String(apiData.id),
    briefingCode: apiData.briefing_code || '',
    title: apiData.title || apiData.project_name || '',
    description: apiData.description || '',
    partnerId: apiData.partner_id ? String(apiData.partner_id) : '',
    partnerName: apiData.partner_name || '',
    briefingDate: apiData.briefing_date || '',
    briefingTime: apiData.briefing_time || '',
    location: apiData.location || '',
    address: apiData.address || '',
    status: (apiData.status as SiteBriefing['status']) || 'scheduled',
    bidStatus: (apiData.bid_status as SiteBriefing['bidStatus']) || 'pending',
    bidDate: apiData.bid_date,
    attendee: attendeeJson, // JSON 문자열로 저장 (parseAttendeeItems에서 파싱)
    attendees: [],
    attendeeCount: apiData.attendee_count || 0,
    attendanceStatus: (apiData.attendance_status as SiteBriefing['attendanceStatus']) || 'scheduled',
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
    createdBy: apiData.created_by || '',
  };
}

/**
 * SiteBriefingFormData → API 요청 데이터 변환
 */
function transformFormDataToApi(data: SiteBriefingFormData): Record<string, unknown> {
  // attendeeItems 배열을 백엔드 형식으로 변환
  // - id가 있으면 internal (직원), 없으면 external (외부인/직접입력)
  const attendees = data.attendeeItems && data.attendeeItems.length > 0
    ? data.attendeeItems.map(item => ({
        ...item,
        type: item.id ? 'internal' : 'external',
      }))
    : null;

  return {
    briefing_code: data.briefingCode,
    title: data.projectName,
    description: data.workReport,
    partner_id: data.partnerId ? Number(data.partnerId) : null,
    partner_name: data.partnerName,
    briefing_date: data.briefingDate,
    briefing_time: data.briefingTime,
    briefing_type: data.briefingType,
    location: data.location,
    attendees: attendees, // 백엔드 필드명: attendees (복수형, array)
    attendance_status: data.attendanceStatus,
    project_name: data.projectName,
    bid_date: data.bidDate,
    site_count: data.siteCount,
    construction_start_date: data.constructionStartDate,
    construction_end_date: data.constructionEndDate,
    vat_type: data.vatType,
    work_report: data.workReport,
  };
}

// 현장설명회 목록 조회
export async function getSiteBriefingList(
  filter?: SiteBriefingFilter
): Promise<{ success: boolean; data?: SiteBriefingListResponse; error?: string }> {
  try {
    // API 쿼리 파라미터 구성 (모든 값을 문자열로 변환)
    const params: Record<string, string> = {
      per_page: String(filter?.size ?? 20),
      page: String(filter?.page ?? 1),
    };

    if (filter?.search) {
      params.search = filter.search;
    }
    if (filter?.status && filter.status !== 'all') {
      params.status = filter.status;
    }
    if (filter?.bidStatus && filter.bidStatus !== 'all') {
      params.bid_status = filter.bidStatus;
    }
    if (filter?.partnerId) {
      params.partner_id = filter.partnerId;
    }
    if (filter?.startDate) {
      params.start_date = filter.startDate;
    }
    if (filter?.endDate) {
      params.end_date = filter.endDate;
    }
    if (filter?.sortBy) {
      const sortMapping: Record<string, { sort_by: string; sort_dir: string }> = {
        latest: { sort_by: 'created_at', sort_dir: 'desc' },
        oldest: { sort_by: 'created_at', sort_dir: 'asc' },
        dateAsc: { sort_by: 'briefing_date', sort_dir: 'asc' },
        dateDesc: { sort_by: 'briefing_date', sort_dir: 'desc' },
      };
      const sort = sortMapping[filter.sortBy];
      if (sort) {
        params.sort_by = sort.sort_by;
        params.sort_dir = sort.sort_dir;
      }
    }

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

    const apiData = response.data;
    const items = apiData.data.map(transformSiteBriefing);

    return {
      success: true,
      data: {
        items,
        total: apiData.total,
        page: apiData.current_page,
        size: apiData.per_page,
        totalPages: apiData.last_page,
      },
    };
  } catch (error) {
    console.error('getSiteBriefingList error:', error);
    return { success: false, error: '현장설명회 목록 조회에 실패했습니다.' };
  }
}

// 현장설명회 상세 조회
export async function getSiteBriefing(
  id: string
): Promise<{ success: boolean; data?: SiteBriefing; error?: string }> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: ApiSiteBriefing;
    }>(`/site-briefings/${id}`);

    return { success: true, data: transformSiteBriefing(response.data) };
  } catch (error) {
    console.error('getSiteBriefing error:', error);
    return { success: false, error: '현장설명회 조회에 실패했습니다.' };
  }
}

// 현장설명회 통계 조회
export async function getSiteBriefingStats(): Promise<{ success: boolean; data?: SiteBriefingStats; error?: string }> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: ApiSiteBriefingStats;
    }>('/site-briefings/stats');

    return { success: true, data: response.data };
  } catch (error) {
    console.error('getSiteBriefingStats error:', error);
    return { success: false, error: '통계 조회에 실패했습니다.' };
  }
}

// ========================================
// API 함수 (CRUD)
// ========================================

/**
 * 현장설명회 등록
 * POST /api/v1/site-briefings
 */
export async function createSiteBriefing(data: SiteBriefingFormData): Promise<{
  success: boolean;
  data?: SiteBriefing;
  error?: string;
}> {
  try {
    const apiData = transformFormDataToApi(data);
    const response = await apiClient.post<{ success: boolean; data: ApiSiteBriefing }>('/site-briefings', apiData);
    return { success: true, data: transformSiteBriefing(response.data) };
  } catch (error) {
    console.error('현장설명회 등록 오류:', error);
    return { success: false, error: '현장설명회 등록에 실패했습니다.' };
  }
}

/**
 * 현장설명회 수정
 * PUT /api/v1/site-briefings/{id}
 */
export async function updateSiteBriefing(id: string, data: SiteBriefingFormData): Promise<{
  success: boolean;
  data?: SiteBriefing;
  error?: string;
}> {
  try {
    const apiData = transformFormDataToApi(data);
    const response = await apiClient.put<{ success: boolean; data: ApiSiteBriefing }>(`/site-briefings/${id}`, apiData);
    return { success: true, data: transformSiteBriefing(response.data) };
  } catch (error) {
    console.error('현장설명회 수정 오류:', error);
    return { success: false, error: '현장설명회 수정에 실패했습니다.' };
  }
}

/**
 * 현장설명회 삭제
 * DELETE /api/v1/site-briefings/{id}
 */
export async function deleteSiteBriefing(id: string): Promise<{ success: boolean; error?: string }> {
  try {
    await apiClient.delete(`/site-briefings/${id}`);
    return { success: true };
  } catch (error) {
    console.error('현장설명회 삭제 오류:', error);
    return { success: false, error: '현장설명회 삭제에 실패했습니다.' };
  }
}

/**
 * 현장설명회 일괄 삭제
 * DELETE /api/v1/site-briefings/bulk
 */
export async function deleteSiteBriefings(ids: string[]): Promise<{ success: boolean; deletedCount?: number; error?: string }> {
  try {
    await apiClient.delete('/site-briefings/bulk', {
      data: { ids: ids.map((id) => Number(id)) },
    });
    return { success: true, deletedCount: ids.length };
  } catch (error) {
    console.error('현장설명회 일괄 삭제 오류:', error);
    return { success: false, error: '일괄 삭제에 실패했습니다.' };
  }
}
