'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  CalendarSchedule,
  CalendarScheduleType,
  CalendarStats,
  CalendarScheduleFormData,
  BulkScheduleItem,
} from './types';

// ===== API 응답 타입 =====
interface ScheduleApiData {
  id: number;
  name: string;
  type: string;
  start_date: string;
  end_date: string;
  days: number;
  is_recurring: boolean;
  memo: string | null;
  created_at: string;
  updated_at: string;
}

interface StatsApiData {
  total_count?: number;
  total_holiday_days?: number;
  public_holiday_count?: number;
}

// ===== 유형 매핑: API(snake_case) → Frontend(camelCase) =====
const API_TYPE_TO_FRONTEND: Record<string, CalendarScheduleType> = {
  public_holiday: 'publicHoliday',
  temporary_holiday: 'temporaryHoliday',
  substitute_holiday: 'substituteHoliday',
  tax_deadline: 'taxDeadline',
  company_event: 'companyEvent',
};

const FRONTEND_TYPE_TO_API: Record<CalendarScheduleType, string> = {
  publicHoliday: 'public_holiday',
  temporaryHoliday: 'temporary_holiday',
  substituteHoliday: 'substitute_holiday',
  taxDeadline: 'tax_deadline',
  companyEvent: 'company_event',
};

// ===== 변환 함수 =====
function transformApiToFrontend(data: ScheduleApiData): CalendarSchedule {
  return {
    id: String(data.id),
    name: data.name,
    type: API_TYPE_TO_FRONTEND[data.type] || ('companyEvent' as CalendarScheduleType),
    startDate: data.start_date,
    endDate: data.end_date,
    days: data.days,
    isRecurring: data.is_recurring,
    memo: data.memo || '',
  };
}

function transformFrontendToApi(data: CalendarScheduleFormData): Record<string, unknown> {
  return {
    name: data.name,
    type: FRONTEND_TYPE_TO_API[data.type],
    start_date: data.startDate,
    end_date: data.endDate,
    is_recurring: data.isRecurring,
    memo: data.memo || null,
  };
}

// ===== 일정 목록 조회 =====
export async function getCalendarSchedules(
  year: number,
  type?: string
): Promise<ActionResult<CalendarSchedule[]>> {
  const result = await executeServerAction<ScheduleApiData[]>({
    url: buildApiUrl('/api/v1/calendar-schedules', {
      year,
      type: type && type !== 'all' ? FRONTEND_TYPE_TO_API[type as CalendarScheduleType] : undefined,
    }),
    errorMessage: '달력 일정 목록을 불러오는데 실패했습니다.',
  });

  if (!result.success || !result.data) {
    return { success: false, error: result.error };
  }

  return {
    success: true,
    data: result.data.map(transformApiToFrontend),
  };
}

// ===== 통계 조회 =====
export async function getCalendarStats(year: number): Promise<ActionResult<CalendarStats>> {
  return executeServerAction<StatsApiData, CalendarStats>({
    url: buildApiUrl('/api/v1/calendar-schedules/stats', { year }),
    transform: (data) => ({
      totalCount: data.total_count ?? 0,
      totalHolidayDays: data.total_holiday_days ?? 0,
      publicHolidayCount: data.public_holiday_count ?? 0,
    }),
    errorMessage: '달력 통계 조회에 실패했습니다.',
  });
}

// ===== 단건 조회 =====
export async function getCalendarSchedule(id: string): Promise<ActionResult<CalendarSchedule>> {
  return executeServerAction<ScheduleApiData, CalendarSchedule>({
    url: buildApiUrl(`/api/v1/calendar-schedules/${id}`),
    transform: transformApiToFrontend,
    errorMessage: '일정 정보를 불러오는데 실패했습니다.',
  });
}

// ===== 등록 =====
export async function createCalendarSchedule(
  data: CalendarScheduleFormData
): Promise<ActionResult<CalendarSchedule>> {
  return executeServerAction<ScheduleApiData, CalendarSchedule>({
    url: buildApiUrl('/api/v1/calendar-schedules'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: transformApiToFrontend,
    errorMessage: '일정 등록에 실패했습니다.',
  });
}

// ===== 수정 =====
export async function updateCalendarSchedule(
  id: string,
  data: CalendarScheduleFormData
): Promise<ActionResult<CalendarSchedule>> {
  return executeServerAction<ScheduleApiData, CalendarSchedule>({
    url: buildApiUrl(`/api/v1/calendar-schedules/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: transformApiToFrontend,
    errorMessage: '일정 수정에 실패했습니다.',
  });
}

// ===== 삭제 =====
export async function deleteCalendarSchedule(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/calendar-schedules/${id}`),
    method: 'DELETE',
    errorMessage: '일정 삭제에 실패했습니다.',
  });
}

// ===== 대량 등록 =====
export async function bulkCreateCalendarSchedules(
  items: BulkScheduleItem[]
): Promise<ActionResult> {
  const body = items.map((item) => ({
    name: item.name,
    type: FRONTEND_TYPE_TO_API[item.type],
    start_date: item.startDate,
    end_date: item.endDate,
    is_recurring: false,
    memo: null,
  }));

  return executeServerAction({
    url: buildApiUrl('/api/v1/calendar-schedules/bulk'),
    method: 'POST',
    body: { schedules: body },
    errorMessage: '대량 등록에 실패했습니다.',
  });
}
