/**
 * 팝업관리 유틸리티 함수
 */

import type { Popup, PopupFormData, PopupTarget, PopupStatus } from './types';
import { toDateString } from '@/lib/utils/date';

// ============================================
// API 응답 타입 정의
// ============================================

// 팝업 API 응답 데이터 타입
export interface PopupApiData {
  id: number;
  tenant_id: number;
  target_type: 'all' | 'department';
  target_id: number | null;
  title: string;
  content: string;
  status: 'active' | 'inactive';
  started_at: string | null;
  ended_at: string | null;
  options: Record<string, unknown> | null;
  created_by: number | null;
  updated_by: number | null;
  deleted_by: number | null;
  created_at: string;
  updated_at: string;
  deleted_at: string | null;
  department?: {
    id: number;
    name: string;
  };
  creator?: {
    id: number;
    name: string;
  };
}

// ============================================
// 변환 함수
// ============================================

/**
 * API 데이터 → 프론트엔드 타입 변환
 */
export function transformApiToFrontend(apiData: PopupApiData): Popup {
  return {
    id: String(apiData.id),
    target: apiData.target_type as PopupTarget,
    targetId: apiData.target_id,
    targetName: apiData.target_type === 'department'
      ? apiData.department?.name
      : undefined,
    title: apiData.title,
    content: apiData.content,
    status: apiData.status as PopupStatus,
    author: apiData.creator?.name || '관리자',
    authorId: apiData.created_by ? String(apiData.created_by) : '',
    createdAt: toDateString(apiData.created_at),
    startDate: toDateString(apiData.started_at),
    endDate: toDateString(apiData.ended_at),
  };
}

/**
 * 프론트엔드 데이터 → API 요청 형식 변환
 */
export function transformFrontendToApi(data: PopupFormData): Record<string, unknown> {
  return {
    target_type: data.target,
    target_id: data.target === 'department' && data.targetDepartmentId
      ? parseInt(data.targetDepartmentId)
      : null,
    title: data.title,
    content: data.content,
    status: data.status,
    started_at: data.startDate || null,
    ended_at: data.endDate || null,
  };
}