'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { NotificationSettings } from './types';
import { DEFAULT_NOTIFICATION_SETTINGS } from './types';

// ===== 알림 설정 조회 =====
export async function getNotificationSettings(): Promise<{
  success: boolean; data: NotificationSettings; error?: string; __authError?: boolean;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/settings/notifications'),
    transform: (data: Record<string, unknown>) => transformApiToFrontend(data),
    errorMessage: '알림 설정 조회에 실패했습니다.',
  });

  // 인증 에러는 전파, 그 외 에러는 기본값 반환 (설정 미존재 시 정상 동작)
  if (result.__authError) {
    return { success: false, data: DEFAULT_NOTIFICATION_SETTINGS, error: result.error, __authError: true };
  }
  if (!result.success || !result.data) {
    return { success: true, data: DEFAULT_NOTIFICATION_SETTINGS };
  }
  return { success: true, data: result.data };
}

// ===== 알림 설정 저장 =====
export async function saveNotificationSettings(settings: NotificationSettings): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/settings/notifications'),
    method: 'PUT',
    body: transformFrontendToApi(settings),
    errorMessage: '알림 설정 저장에 실패했습니다.',
  });
}

// ===== API → Frontend 변환 (기본값과 병합) =====
function transformApiToFrontend(apiData: Record<string, unknown>): NotificationSettings {
  // API 응답에 soundType이 없을 수 있으므로 기본값과 병합
  const data = apiData as Partial<NotificationSettings>;

  return {
    notice: {
      enabled: data.notice?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.notice.enabled,
      notice: { ...DEFAULT_NOTIFICATION_SETTINGS.notice.notice, ...data.notice?.notice },
      event: { ...DEFAULT_NOTIFICATION_SETTINGS.notice.event, ...data.notice?.event },
    },
    schedule: {
      enabled: data.schedule?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.schedule.enabled,
      vatReport: { ...DEFAULT_NOTIFICATION_SETTINGS.schedule.vatReport, ...data.schedule?.vatReport },
      incomeTaxReport: { ...DEFAULT_NOTIFICATION_SETTINGS.schedule.incomeTaxReport, ...data.schedule?.incomeTaxReport },
    },
    vendor: {
      enabled: data.vendor?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.vendor.enabled,
      newVendor: { ...DEFAULT_NOTIFICATION_SETTINGS.vendor.newVendor, ...data.vendor?.newVendor },
      creditRating: { ...DEFAULT_NOTIFICATION_SETTINGS.vendor.creditRating, ...data.vendor?.creditRating },
    },
    attendance: {
      enabled: data.attendance?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.attendance.enabled,
      annualLeave: { ...DEFAULT_NOTIFICATION_SETTINGS.attendance.annualLeave, ...data.attendance?.annualLeave },
      clockIn: { ...DEFAULT_NOTIFICATION_SETTINGS.attendance.clockIn, ...data.attendance?.clockIn },
      late: { ...DEFAULT_NOTIFICATION_SETTINGS.attendance.late, ...data.attendance?.late },
      absent: { ...DEFAULT_NOTIFICATION_SETTINGS.attendance.absent, ...data.attendance?.absent },
    },
    order: {
      enabled: data.order?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.order.enabled,
      salesOrder: { ...DEFAULT_NOTIFICATION_SETTINGS.order.salesOrder, ...data.order?.salesOrder },
      purchaseOrder: { ...DEFAULT_NOTIFICATION_SETTINGS.order.purchaseOrder, ...data.order?.purchaseOrder },
      approvalRequest: { ...DEFAULT_NOTIFICATION_SETTINGS.order.approvalRequest, ...data.order?.approvalRequest },
    },
    approval: {
      enabled: data.approval?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.approval.enabled,
      approvalRequest: { ...DEFAULT_NOTIFICATION_SETTINGS.approval.approvalRequest, ...data.approval?.approvalRequest },
      draftApproved: { ...DEFAULT_NOTIFICATION_SETTINGS.approval.draftApproved, ...data.approval?.draftApproved },
      draftRejected: { ...DEFAULT_NOTIFICATION_SETTINGS.approval.draftRejected, ...data.approval?.draftRejected },
      draftCompleted: { ...DEFAULT_NOTIFICATION_SETTINGS.approval.draftCompleted, ...data.approval?.draftCompleted },
    },
    production: {
      enabled: data.production?.enabled ?? DEFAULT_NOTIFICATION_SETTINGS.production.enabled,
      safetyStock: { ...DEFAULT_NOTIFICATION_SETTINGS.production.safetyStock, ...data.production?.safetyStock },
      productionComplete: { ...DEFAULT_NOTIFICATION_SETTINGS.production.productionComplete, ...data.production?.productionComplete },
    },
  };
}

// ===== Frontend → API 변환 =====
function transformFrontendToApi(settings: NotificationSettings): Record<string, unknown> {
  // 프론트엔드 형식이 이미 API 형식과 동일하다고 가정
  // 필요시 camelCase → snake_case 변환
  return settings as unknown as Record<string, unknown>;
}