'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import type { LeavePolicySettings } from './types';

const API_URL = process.env.NEXT_PUBLIC_API_URL;

// ===== API 응답 타입 =====
interface LeavePolicyApi {
  id: number;
  tenant_id: number;
  standard_type: 'fiscal' | 'hire';
  fiscal_start_month: number;
  fiscal_start_day: number;
  default_annual_leave: number;
  additional_leave_per_year: number;
  max_annual_leave: number;
  carry_over_enabled: boolean;
  carry_over_max_days: number;
  carry_over_expiry_months: number;
  created_at?: string;
  updated_at?: string;
}

// ===== API → Frontend 변환 =====
function transformLeavePolicy(data: LeavePolicyApi): LeavePolicySettings {
  return {
    standardType: data.standard_type,
    fiscalStartMonth: data.fiscal_start_month,
    fiscalStartDay: data.fiscal_start_day,
    defaultAnnualLeave: data.default_annual_leave,
    additionalLeavePerYear: data.additional_leave_per_year,
    maxAnnualLeave: data.max_annual_leave,
    carryOverEnabled: data.carry_over_enabled,
    carryOverMaxDays: data.carry_over_max_days,
    carryOverExpiryMonths: data.carry_over_expiry_months,
  };
}

// ===== Frontend → API 변환 =====
function transformToApi(data: Partial<LeavePolicySettings>): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  if (data.standardType !== undefined) result.standard_type = data.standardType;
  if (data.fiscalStartMonth !== undefined) result.fiscal_start_month = data.fiscalStartMonth;
  if (data.fiscalStartDay !== undefined) result.fiscal_start_day = data.fiscalStartDay;
  if (data.defaultAnnualLeave !== undefined) result.default_annual_leave = data.defaultAnnualLeave;
  if (data.additionalLeavePerYear !== undefined) result.additional_leave_per_year = data.additionalLeavePerYear;
  if (data.maxAnnualLeave !== undefined) result.max_annual_leave = data.maxAnnualLeave;
  if (data.carryOverEnabled !== undefined) result.carry_over_enabled = data.carryOverEnabled;
  if (data.carryOverMaxDays !== undefined) result.carry_over_max_days = data.carryOverMaxDays;
  if (data.carryOverExpiryMonths !== undefined) result.carry_over_expiry_months = data.carryOverExpiryMonths;
  return result;
}

// ===== 휴가 정책 조회 =====
export async function getLeavePolicy(): Promise<ActionResult<LeavePolicySettings>> {
  return executeServerAction({
    url: `${API_URL}/api/v1/leave-policy`,
    transform: (data: LeavePolicyApi) => transformLeavePolicy(data),
    errorMessage: '휴가 정책 조회에 실패했습니다.',
  });
}

// ===== 휴가 정책 업데이트 =====
export async function updateLeavePolicy(
  data: Partial<LeavePolicySettings>
): Promise<ActionResult<LeavePolicySettings>> {
  return executeServerAction({
    url: `${API_URL}/api/v1/leave-policy`,
    method: 'PUT',
    body: transformToApi(data),
    transform: (data: LeavePolicyApi) => transformLeavePolicy(data),
    errorMessage: '휴가 정책 저장에 실패했습니다.',
  });
}
