'use server';


import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { serverFetch } from '@/lib/api/fetch-wrapper';
import type { LeavePolicySettings } from './types';

// ===== 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<{
  success: boolean;
  data?: LeavePolicySettings;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/leave-policy`;

    const { response, error } = await serverFetch(url, {
      method: 'GET',
      cache: 'no-store',
    });

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response || !response.ok) {
      console.warn('[LeavePolicyActions] GET error:', response?.status);
      return {
        success: false,
        error: `API 오류: ${response?.status}`,
      };
    }

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        error: result.message || '휴가 정책 조회에 실패했습니다.',
      };
    }

    const transformedData = transformLeavePolicy(result.data);

    return {
      success: true,
      data: transformedData,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[LeavePolicyActions] getLeavePolicy error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}

// ===== 휴가 정책 업데이트 =====
export async function updateLeavePolicy(data: Partial<LeavePolicySettings>): Promise<{
  success: boolean;
  data?: LeavePolicySettings;
  error?: string;
  __authError?: boolean;
}> {
  try {
    const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/leave-policy`;
    const apiData = transformToApi(data);

    const { response, error } = await serverFetch(url, {
      method: 'PUT',
      body: JSON.stringify(apiData),
    });

    if (error) {
      return {
        success: false,
        error: error.message,
        __authError: error.code === 'UNAUTHORIZED',
      };
    }

    if (!response || !response.ok) {
      console.warn('[LeavePolicyActions] PUT error:', response?.status);
      return {
        success: false,
        error: `API 오류: ${response?.status}`,
      };
    }

    const result = await response.json();

    if (!result.success) {
      return {
        success: false,
        error: result.message || '휴가 정책 저장에 실패했습니다.',
      };
    }

    const transformedData = transformLeavePolicy(result.data);

    return {
      success: true,
      data: transformedData,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[LeavePolicyActions] updateLeavePolicy error:', error);
    return {
      success: false,
      error: '서버 오류가 발생했습니다.',
    };
  }
}
