/**
 * 결재 양식(approval-forms) 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/approval-forms - 양식 목록 (active)
 * - GET /api/v1/approval-forms/{id} - 양식 상세 (template 포함)
 */

'use server';

import { executeServerAction } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';

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

export interface ApprovalFormItem {
  id: number;
  name: string;
  code: string;
  category: string;
}

export interface ApprovalFormField {
  name: string;
  type: 'text' | 'textarea' | 'number' | 'date' | 'select' | 'checkbox' | 'file' | 'daterange' | 'array';
  label: string;
  required?: boolean;
  options?: string[];
  placeholder?: string;
  description?: string;
  columns?: ApprovalFormField[]; // array 타입의 하위 필드
}

export interface ApprovalFormDetail {
  id: number;
  name: string;
  code: string;
  category: string;
  template: {
    fields: ApprovalFormField[];
  };
}

// category별 그룹 (2단계 Select용)
export interface ApprovalFormCategory {
  category: string;
  categoryLabel: string;
  forms: ApprovalFormItem[];
}

// ============================================
// 공통 자동입력 데이터 타입
// ============================================

export interface CompanyAutoFill {
  companyName: string;
  representativeName: string;
  businessNumber: string;
  address: string;
  phone: string;
  fax: string;
  email: string;
  businessType: string;
  businessCategory: string;
}

export interface EmployeeAutoFill {
  id: string;
  name: string;
  department: string;
  position: string;
  residentNumber: string;
  birthDate: string;
  address: string;
  phone: string;
  joinDate: string;
}

export interface LeaveBalanceAutoFill {
  totalDays: number;
  usedDays: number;
  remainingDays: number;
}

// ============================================
// API 함수
// ============================================

/**
 * 활성 양식 목록 조회
 */
export async function getApprovalForms(): Promise<{ success: boolean; data: ApprovalFormItem[]; error?: string }> {
  const result = await executeServerAction<ApprovalFormItem[] | { data: ApprovalFormItem[] }>({
    url: buildApiUrl('/api/v1/approval-forms'),
    errorMessage: '양식 목록 조회에 실패했습니다.',
  });

  if (!result.success) return { success: false, data: [], error: result.error };

  // API 응답이 배열 또는 { data: [...] } 형태 모두 처리
  const rawData = result.data;
  let forms: ApprovalFormItem[] = [];
  if (Array.isArray(rawData)) {
    forms = rawData;
  } else if (rawData && typeof rawData === 'object' && 'data' in rawData && Array.isArray(rawData.data)) {
    forms = rawData.data;
  }

  return { success: true, data: forms };
}

/**
 * 양식 상세 조회 (template.fields 포함)
 */
export async function getApprovalFormDetail(id: number): Promise<{ success: boolean; data?: ApprovalFormDetail; error?: string }> {
  const result = await executeServerAction<ApprovalFormDetail>({
    url: buildApiUrl(`/api/v1/approval-forms/${id}`),
    errorMessage: '양식 상세 조회에 실패했습니다.',
  });

  if (!result.success) return { success: false, error: result.error };
  return { success: true, data: result.data || undefined };
}

/**
 * 양식 목록을 카테고리별로 그룹핑 (2단계 Select용)
 */
export async function getApprovalFormsByCategory(): Promise<{ success: boolean; data: ApprovalFormCategory[]; error?: string }> {
  const result = await getApprovalForms();
  if (!result.success) return { success: false, data: [], error: result.error };

  const categoryMap = new Map<string, ApprovalFormItem[]>();
  for (const form of result.data) {
    const existing = categoryMap.get(form.category) || [];
    existing.push(form);
    categoryMap.set(form.category, existing);
  }

  const CATEGORY_LABELS: Record<string, string> = {
    '일반': '일반',
    '경비': '경비',
    'hr': '인사',
    'general': '총무',
    'expense': '재무',
    'request': '총무/기타',
    'certificate': '증명서',
    'finance': '재무',
    'document': '문서',
    'proposal': '품의',
    'expense_report': '지출',
    'expense_estimate': '예산',
  };

  const data: ApprovalFormCategory[] = Array.from(categoryMap.entries()).map(([category, forms]) => ({
    category,
    categoryLabel: CATEGORY_LABELS[category] || category,
    forms,
  }));

  return { success: true, data };
}

// ============================================
// 공통 자동입력 함수 (전용 폼에서 사용)
// ============================================

/**
 * 회사 정보 자동입력용 조회
 */
export async function getCompanyAutoFill(): Promise<{ success: boolean; data?: CompanyAutoFill; error?: string }> {
  const result = await executeServerAction<{
    company_name?: string;
    representative_name?: string;
    business_number?: string;
    address?: string;
    phone?: string;
    fax?: string;
    email?: string;
    business_type?: string;
    business_category?: string;
    [key: string]: unknown;
  }>({
    url: buildApiUrl('/api/v1/tenant/company-info'),
    errorMessage: '회사 정보 조회에 실패했습니다.',
  });

  if (!result.success || !result.data) return { success: false, error: result.error };

  const d = result.data;
  return {
    success: true,
    data: {
      companyName: d.company_name || '',
      representativeName: d.representative_name || '',
      businessNumber: d.business_number || '',
      address: d.address || '',
      phone: d.phone || '',
      fax: d.fax || '',
      email: d.email || '',
      businessType: d.business_type || '',
      businessCategory: d.business_category || '',
    },
  };
}

/**
 * 직원 상세 정보 자동입력용 조회
 */
export async function getEmployeeAutoFill(employeeId: string): Promise<{ success: boolean; data?: EmployeeAutoFill; error?: string }> {
  const result = await executeServerAction<{
    id?: number;
    user?: { id?: number; name?: string };
    department?: { id?: number; name?: string } | null;
    position?: { id?: number; name?: string; key?: string } | null;
    resident_number?: string;
    birth_date?: string;
    address?: string;
    phone?: string;
    hire_date?: string;
    [key: string]: unknown;
  }>({
    url: buildApiUrl(`/api/v1/employees/${employeeId}`),
    errorMessage: '직원 정보 조회에 실패했습니다.',
  });

  if (!result.success || !result.data) return { success: false, error: result.error };

  const d = result.data;
  return {
    success: true,
    data: {
      id: String(d.user?.id || d.id || ''),
      name: d.user?.name || '',
      department: d.department?.name || '',
      position: d.position?.name || '',
      residentNumber: d.resident_number || '',
      birthDate: d.birth_date || '',
      address: d.address || '',
      phone: d.phone || '',
      joinDate: d.hire_date || '',
    },
  };
}

/**
 * 직원 목록 조회 (Select 옵션용)
 */
export async function getEmployeeOptions(): Promise<{ success: boolean; data: { id: string; name: string; department: string }[]; error?: string }> {
  const result = await executeServerAction<{
    data?: Array<{
      id: number;
      user?: { id?: number; name?: string };
      department?: { name?: string } | null;
    }>;
  }>({
    url: buildApiUrl('/api/v1/employees', { per_page: 200, status: 'active' }),
    errorMessage: '직원 목록 조회에 실패했습니다.',
  });

  if (!result.success || !result.data) return { success: false, data: [], error: result.error };

  const employees = (result.data.data || []).map((e) => ({
    id: String(e.id),
    name: e.user?.name || '',
    department: e.department?.name || '',
  }));

  return { success: true, data: employees };
}

/**
 * 직원 연차 잔여일수 조회
 */
export async function getLeaveBalanceAutoFill(userId: number, year?: number): Promise<{ success: boolean; data?: LeaveBalanceAutoFill; error?: string }> {
  const y = year || new Date().getFullYear();
  const result = await executeServerAction<{
    total_days?: number;
    used_days?: number;
    remaining_days?: number;
    [key: string]: unknown;
  }>({
    url: buildApiUrl(`/api/v1/leaves/balance/${userId}`, { year: y }),
    errorMessage: '연차 잔여일수 조회에 실패했습니다.',
  });

  if (!result.success || !result.data) return { success: false, error: result.error };

  const d = result.data;
  return {
    success: true,
    data: {
      totalDays: d.total_days || 0,
      usedDays: d.used_days || 0,
      remainingDays: d.remaining_days || 0,
    },
  };
}
