'use server';


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

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://sam.kr:8080';

// ===== 타입 정의 =====

// API 응답 타입
interface ApiWorkSetting {
  id: number;
  tenant_id: number;
  work_type: 'fixed' | 'flexible' | 'custom';
  standard_hours: number;
  overtime_hours: number;
  overtime_limit: number;
  work_days: string[] | null;
  start_time: string; // HH:mm:ss
  end_time: string;
  break_minutes: number;
  break_start: string | null;
  break_end: string | null;
  created_at?: string;
  updated_at?: string;
}

// React 폼 데이터 타입 (기존 types.ts의 WorkScheduleSettings와 유사)
export interface WorkSettingFormData {
  workType: 'fixed' | 'flexible' | 'custom';
  workDays: string[];
  workStartTime: string; // HH:mm
  workEndTime: string;
  weeklyWorkHours: number;
  weeklyOvertimeHours: number;
  overtimeLimit: number;
  breakMinutes: number;
  breakStartTime: string; // HH:mm
  breakEndTime: string;
}

// ===== 데이터 변환 =====

/**
 * API → React 변환
 */
function transformFromApi(data: ApiWorkSetting): WorkSettingFormData {
  return {
    workType: data.work_type,
    workDays: data.work_days || ['mon', 'tue', 'wed', 'thu', 'fri'],
    workStartTime: data.start_time?.substring(0, 5) || '09:00',
    workEndTime: data.end_time?.substring(0, 5) || '18:00',
    weeklyWorkHours: data.standard_hours,
    weeklyOvertimeHours: data.overtime_hours,
    overtimeLimit: data.overtime_limit,
    breakMinutes: data.break_minutes,
    breakStartTime: data.break_start?.substring(0, 5) || '12:00',
    breakEndTime: data.break_end?.substring(0, 5) || '13:00',
  };
}

/**
 * React → API 변환
 */
function transformToApi(data: Partial<WorkSettingFormData>): Record<string, unknown> {
  const apiData: Record<string, unknown> = {};
  if (data.workType !== undefined) apiData.work_type = data.workType;
  if (data.workDays !== undefined) apiData.work_days = data.workDays;
  if (data.workStartTime !== undefined) apiData.start_time = `${data.workStartTime}:00`;
  if (data.workEndTime !== undefined) apiData.end_time = `${data.workEndTime}:00`;
  if (data.weeklyWorkHours !== undefined) apiData.standard_hours = data.weeklyWorkHours;
  if (data.weeklyOvertimeHours !== undefined) apiData.overtime_hours = data.weeklyOvertimeHours;
  if (data.overtimeLimit !== undefined) apiData.overtime_limit = data.overtimeLimit;
  if (data.breakMinutes !== undefined) apiData.break_minutes = data.breakMinutes;
  if (data.breakStartTime !== undefined) apiData.break_start = `${data.breakStartTime}:00`;
  if (data.breakEndTime !== undefined) apiData.break_end = `${data.breakEndTime}:00`;
  return apiData;
}

// ===== API 호출 =====

/**
 * 근무 설정 조회
 */
export async function getWorkSetting(): Promise<ActionResult<WorkSettingFormData>> {
  return executeServerAction({
    url: `${API_BASE_URL}/api/v1/settings/work`,
    transform: (data: ApiWorkSetting) => transformFromApi(data),
    errorMessage: '근무 설정을 불러오는데 실패했습니다.',
  });
}

/**
 * 근무 설정 수정
 */
export async function updateWorkSetting(
  data: Partial<WorkSettingFormData>
): Promise<ActionResult<WorkSettingFormData>> {
  return executeServerAction({
    url: `${API_BASE_URL}/api/v1/settings/work`,
    method: 'PUT',
    body: transformToApi(data),
    transform: (data: ApiWorkSetting) => transformFromApi(data),
    errorMessage: '근무 설정 저장에 실패했습니다.',
  });
}