/**
 * 참조함 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/approvals/reference - 참조함 목록 조회
 * - POST /api/v1/approvals/{id}/read - 열람 처리
 * - POST /api/v1/approvals/{id}/unread - 미열람 처리
 */

'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { PaginatedApiResponse } from '@/lib/api/types';
import type { ReferenceRecord, ApprovalType, DocumentStatus } from './types';

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

interface ReferenceApiData {
  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?: ReferenceStepApiData[];
  created_at: string;
  updated_at: string;
}

interface ReferenceStepApiData {
  id: number;
  step_order: number;
  step_type: string;
  approver_id: number;
  approver?: { id: number; name: string; position?: string; department?: { name: string } };
  is_read: boolean;
  read_at?: string;
}

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

function mapApiStatus(apiStatus: string): DocumentStatus {
  const statusMap: Record<string, DocumentStatus> = {
    'draft': 'pending', 'pending': 'pending', 'in_progress': 'pending',
    'approved': 'approved', 'rejected': 'rejected',
    'cancelled': 'cancelled', 'on_hold': 'on_hold',
  };
  return statusMap[apiStatus] || 'pending';
}

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

function transformApiToFrontend(data: ReferenceApiData): ReferenceRecord {
  const referenceStep = data.steps?.find(s => s.step_type === 'reference');
  const isRead = referenceStep?.is_read ?? false;
  const readAt = referenceStep?.read_at;

  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 || '',
    documentStatus: mapApiStatus(data.status),
    readStatus: isRead ? 'read' : 'unread',
    readAt: readAt ? readAt.replace('T', ' ').substring(0, 16) : undefined,
    createdAt: data.created_at,
    updatedAt: data.updated_at,
  };
}

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

export async function getReferences(params?: {
  page?: number; per_page?: number; search?: string; is_read?: boolean;
  approval_type?: string; sort_by?: string; sort_dir?: 'asc' | 'desc';
}): Promise<{ data: ReferenceRecord[]; total: number; lastPage: number }> {
  const result = await executeServerAction<PaginatedApiResponse<ReferenceApiData>>({
    url: buildApiUrl('/api/v1/approvals/reference', {
      page: params?.page,
      per_page: params?.per_page,
      search: params?.search,
      is_read: params?.is_read !== undefined ? (params.is_read ? '1' : '0') : undefined,
      approval_type: params?.approval_type !== 'all' ? params?.approval_type : undefined,
      sort_by: params?.sort_by,
      sort_dir: params?.sort_dir,
    }),
    errorMessage: '참조 목록 조회에 실패했습니다.',
  });

  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 getReferenceSummary(): Promise<{ all: number; read: number; unread: number } | null> {
  try {
    const allResult = await getReferences({ per_page: 1 });
    const readResult = await getReferences({ per_page: 1, is_read: true });
    const unreadResult = await getReferences({ per_page: 1, is_read: false });
    return { all: allResult.total, read: readResult.total, unread: unreadResult.total };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    return null;
  }
}

export async function markAsRead(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/approvals/${id}/read`),
    method: 'POST',
    body: {},
    errorMessage: '열람 처리에 실패했습니다.',
  });
}

export async function markAsUnread(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/approvals/${id}/unread`),
    method: 'POST',
    body: {},
    errorMessage: '미열람 처리에 실패했습니다.',
  });
}

export async function markAsReadBulk(ids: string[]): Promise<{ success: boolean; failedIds?: string[]; error?: string }> {
  const failedIds: string[] = [];
  for (const id of ids) {
    const result = await markAsRead(id);
    if (!result.success) failedIds.push(id);
  }
  if (failedIds.length > 0) {
    return { success: false, failedIds, error: `${failedIds.length}건의 열람 처리에 실패했습니다.` };
  }
  return { success: true };
}

export async function markAsUnreadBulk(ids: string[]): Promise<{ success: boolean; failedIds?: string[]; error?: string }> {
  const failedIds: string[] = [];
  for (const id of ids) {
    const result = await markAsUnread(id);
    if (!result.success) failedIds.push(id);
  }
  if (failedIds.length > 0) {
    return { success: false, failedIds, error: `${failedIds.length}건의 미열람 처리에 실패했습니다.` };
  }
  return { success: true };
}
