/**
 * 결재함 서버 액션
 *
 * API Endpoints:
 * - GET /api/v1/approvals/inbox - 결재함 목록 조회
 * - GET /api/v1/approvals/inbox/summary - 결재함 통계
 * - POST /api/v1/approvals/{id}/approve - 승인 처리
 * - POST /api/v1/approvals/{id}/reject - 반려 처리
 */

'use server';


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

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

interface InboxSummary {
  total: number;
  pending: number;
  approved: number;
  rejected: number;
}

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

interface InboxStepApiData {
  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;
  comment?: string;
}

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

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

function mapTabToApiStatus(tabStatus: string): string | undefined {
  const statusMap: Record<string, string> = {
    'pending': 'requested', 'approved': 'completed', 'rejected': 'rejected',
  };
  return statusMap[tabStatus];
}

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 mapDocumentStatus(status: string): string {
  const statusMap: Record<string, string> = {
    'pending': '진행중', 'approved': '완료', 'rejected': '반려',
  };
  return statusMap[status] || '진행중';
}

function transformApiToFrontend(data: InboxApiData): ApprovalRecord {
  const currentStep = data.steps?.find(s => s.step_type === 'approval' || s.step_type === 'agreement');
  const approver = currentStep?.approver;
  const stepStatus = currentStep?.status || 'pending';

  return {
    id: String(data.id),
    documentNo: data.document_number,
    approvalType: mapApprovalType(data.form?.category),
    documentStatus: mapDocumentStatus(data.status),
    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 || '',
    approvalDate: currentStep?.processed_at?.replace('T', ' ').substring(0, 16),
    approver: approver?.name,
    status: mapApiStatus(stepStatus),
    priority: 'normal',
    createdAt: data.created_at,
    updatedAt: data.updated_at,
  };
}

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

export async function getInbox(params?: {
  page?: number; per_page?: number; search?: string; status?: string;
  approval_type?: string; sort_by?: string; sort_dir?: 'asc' | 'desc';
}): Promise<{ data: ApprovalRecord[]; total: number; lastPage: number; __authError?: boolean }> {
  const result = await executeServerAction<PaginatedApiResponse<InboxApiData>>({
    url: buildApiUrl('/api/v1/approvals/inbox', {
      page: params?.page,
      per_page: params?.per_page,
      search: params?.search,
      status: params?.status && params.status !== 'all' ? mapTabToApiStatus(params.status) : undefined,
      approval_type: params?.approval_type !== 'all' ? params?.approval_type : undefined,
      sort_by: params?.sort_by,
      sort_dir: params?.sort_dir,
    }),
    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 getInboxSummary(): Promise<InboxSummary | null> {
  const result = await executeServerAction<InboxSummary>({
    url: buildApiUrl('/api/v1/approvals/inbox/summary'),
    errorMessage: '결재함 통계 조회에 실패했습니다.',
  });
  return result.success ? result.data || null : null;
}

export async function approveDocument(id: string, comment?: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/approvals/${id}/approve`),
    method: 'POST',
    body: { comment: comment || '' },
    errorMessage: '승인 처리에 실패했습니다.',
  });
}

export async function rejectDocument(id: string, comment: string): Promise<ActionResult> {
  if (!comment?.trim()) return { success: false, error: '반려 사유를 입력해주세요.' };
  return executeServerAction({
    url: buildApiUrl(`/api/v1/approvals/${id}/reject`),
    method: 'POST',
    body: { comment },
    errorMessage: '반려 처리에 실패했습니다.',
  });
}

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

export async function rejectDocumentsBulk(ids: string[], comment: string): Promise<{ success: boolean; failedIds?: string[]; error?: string }> {
  if (!comment?.trim()) return { success: false, error: '반려 사유를 입력해주세요.' };
  const failedIds: string[] = [];
  for (const id of ids) {
    const result = await rejectDocument(id, comment);
    if (!result.success) failedIds.push(id);
  }
  if (failedIds.length > 0) {
    return { success: false, failedIds, error: `${failedIds.length}건의 반려 처리에 실패했습니다.` };
  }
  return { success: true };
}