/**
 * 완료함 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/approvals/completed - 완료함 목록 조회
 * - GET /api/v1/approvals/completed/summary - 완료함 통계
 */

'use server';

import { executeServerAction } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { PaginatedApiResponse } from '@/lib/api/types';
import type { CompletedRecord, CompletedStatus, ApprovalType } from './types';

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

interface CompletedSummary {
  total: number;
  approved: number;
  rejected: number;
}

interface CompletedApiData {
  id: number;
  document_number: string;
  title: string;
  status: string;
  form?: { id: number; name: string; code: string; category: string };
  drafter?: { id: number; name: string; position?: string; department?: { name: string } };
  steps?: Array<{
    id: number;
    step_order: number;
    step_type: string;
    approver_id: number;
    approver?: { id: number; name: string; position?: string; department?: { name: string } };
    status: string;
    processed_at?: string;
  }>;
  created_at: string;
  updated_at: string;
}

// ============================================
// 헬퍼 함수
// ============================================

function mapCompletedStatus(apiStatus: string): CompletedStatus {
  if (apiStatus === 'rejected') return 'rejected';
  return 'approved';
}

function mapApprovalType(formCategory?: string): ApprovalType {
  const typeMap: Record<string, ApprovalType> = {
    'expense_report': 'expense_report',
    'proposal': 'proposal',
    'expense_estimate': 'expense_estimate',
    'document': 'document',
  };
  return typeMap[formCategory || ''] || 'proposal';
}

function transformApiToFrontend(data: CompletedApiData): CompletedRecord {
  // 마지막 처리자 찾기
  const lastProcessedStep = data.steps
    ?.filter(s => s.processed_at)
    .sort((a, b) => (b.processed_at || '').localeCompare(a.processed_at || ''))
    [0];

  return {
    id: String(data.id),
    documentNo: data.document_number,
    approvalType: mapApprovalType(data.form?.category),
    formCode: data.form?.code,
    formName: data.form?.name,
    title: data.title,
    draftDate: data.created_at.replace('T', ' ').substring(0, 16),
    drafter: data.drafter?.name || '',
    drafterDepartment: data.drafter?.department?.name || '',
    drafterPosition: data.drafter?.position || '',
    completedDate: lastProcessedStep?.processed_at?.replace('T', ' ').substring(0, 16) || '',
    completedBy: lastProcessedStep?.approver?.name || '',
    status: mapCompletedStatus(data.status),
    createdAt: data.created_at,
    updatedAt: data.updated_at,
  };
}

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

export async function getCompleted(params?: {
  page?: number; per_page?: number; search?: string; status?: string;
  approval_type?: string; sort_by?: string; sort_dir?: 'asc' | 'desc';
  start_date?: string; end_date?: string;
}): Promise<{ data: CompletedRecord[]; total: number; lastPage: number; __authError?: boolean }> {
  const result = await executeServerAction<PaginatedApiResponse<CompletedApiData>>({
    url: buildApiUrl('/api/v1/approvals/completed', {
      page: params?.page,
      per_page: params?.per_page,
      search: params?.search,
      status: params?.status && params.status !== 'all' ? params.status : undefined,
      approval_type: params?.approval_type !== 'all' ? params?.approval_type : undefined,
      sort_by: params?.sort_by,
      sort_dir: params?.sort_dir,
      start_date: params?.start_date,
      end_date: params?.end_date,
    }),
    errorMessage: '완료함 목록 조회에 실패했습니다.',
  });

  if (result.__authError) return { data: [], total: 0, lastPage: 1, __authError: true };
  if (!result.success || !result.data?.data) return { data: [], total: 0, lastPage: 1 };

  return {
    data: result.data.data.map(transformApiToFrontend),
    total: result.data.total,
    lastPage: result.data.last_page,
  };
}

export async function getCompletedSummary(): Promise<CompletedSummary | null> {
  const result = await executeServerAction<CompletedSummary>({
    url: buildApiUrl('/api/v1/approvals/completed/summary'),
    errorMessage: '완료함 통계 조회에 실패했습니다.',
  });
  return result.success ? result.data || null : null;
}
