'use server';

/**
 * 점검표 관리 Server Actions
 *
 * 현재: Mock 데이터 기반
 * 추후: executeServerAction으로 백엔드 API 연동 전환
 */

import type {
  Checklist,
  ChecklistFormData,
  ChecklistItem,
  ChecklistItemFormData,
  ChecklistDocument,
} from '@/types/checklist';

// ============================================================================
// Mock 데이터
// ============================================================================

const MOCK_DOCUMENTS: ChecklistDocument[] = [
  {
    id: 'doc-1',
    itemId: 'item-1',
    documentCode: 'QM-std-1-1-1',
    documentName: '문서명.pdf',
    revision: 'REV12',
    effectiveDate: '2026-01-05',
    order: 1,
  },
  {
    id: 'doc-2',
    itemId: 'item-1',
    documentCode: 'QM-std-1-1-1',
    documentName: '문서명.pdf',
    revision: 'REV12',
    effectiveDate: '2026-01-06',
    order: 2,
  },
];

const MOCK_ITEMS: ChecklistItem[] = [
  {
    id: 'item-1',
    checklistId: 'cl-1',
    itemCode: '123123',
    itemName: '1. 수입검사 기준 확인',
    description: '소개 문구',
    documentCount: 3,
    status: '사용',
    order: 1,
    documents: MOCK_DOCUMENTS,
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
  },
  {
    id: 'item-2',
    checklistId: 'cl-1',
    itemCode: '123123',
    itemName: '항목명',
    description: '',
    documentCount: 3,
    status: '사용',
    order: 2,
    documents: [],
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
  },
  {
    id: 'item-3',
    checklistId: 'cl-1',
    itemCode: '123123',
    itemName: '항목명',
    description: '',
    documentCount: 3,
    status: '사용',
    order: 3,
    documents: [],
    createdAt: '2026-01-01T00:00:00Z',
    updatedAt: '2026-01-01T00:00:00Z',
  },
];

const MOCK_CHECKLISTS: Checklist[] = [
  {
    id: 'cl-1',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '사용',
    order: 1,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
  {
    id: 'cl-2',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '미사용',
    order: 2,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
  {
    id: 'cl-3',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '사용',
    order: 3,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
  {
    id: 'cl-4',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '미사용',
    order: 4,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
  {
    id: 'cl-5',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '사용',
    order: 5,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
  {
    id: 'cl-6',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '미사용',
    order: 6,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
  {
    id: 'cl-7',
    checklistCode: '변호명',
    checklistName: '점검표명',
    itemCount: 3,
    documentCount: 6,
    status: '사용',
    order: 7,
    createdAt: '2025-09-01T00:00:00Z',
    updatedAt: '2025-09-01T00:00:00Z',
  },
];

// ============================================================================
// 점검표 CRUD
// ============================================================================

export async function getChecklistList(): Promise<{
  success: boolean;
  data?: { items: Checklist[] };
  error?: string;
}> {
  return { success: true, data: { items: [...MOCK_CHECKLISTS] } };
}

export async function getChecklistById(id: string): Promise<{
  success: boolean;
  data?: Checklist;
  error?: string;
}> {
  const checklist = MOCK_CHECKLISTS.find((c) => c.id === id);
  if (!checklist) return { success: false, error: '점검표를 찾을 수 없습니다.' };
  return { success: true, data: { ...checklist } };
}

export async function createChecklist(data: ChecklistFormData): Promise<{
  success: boolean;
  data?: Checklist;
  error?: string;
}> {
  const newChecklist: Checklist = {
    id: `cl-${Date.now()}`,
    checklistCode: `CL-${String(MOCK_CHECKLISTS.length + 1).padStart(3, '0')}`,
    checklistName: data.checklistName,
    itemCount: 0,
    documentCount: 0,
    status: data.status,
    order: MOCK_CHECKLISTS.length + 1,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
  return { success: true, data: newChecklist };
}

export async function updateChecklist(
  id: string,
  data: ChecklistFormData
): Promise<{ success: boolean; data?: Checklist; error?: string }> {
  const checklist = MOCK_CHECKLISTS.find((c) => c.id === id);
  if (!checklist) return { success: false, error: '점검표를 찾을 수 없습니다.' };
  const updated = {
    ...checklist,
    checklistName: data.checklistName,
    status: data.status,
    updatedAt: new Date().toISOString(),
  };
  return { success: true, data: updated };
}

export async function deleteChecklist(_id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  return { success: true };
}

export async function deleteChecklists(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  return { success: true, deletedCount: ids.length };
}

export async function toggleChecklistStatus(id: string): Promise<{
  success: boolean;
  data?: Checklist;
  error?: string;
}> {
  const checklist = MOCK_CHECKLISTS.find((c) => c.id === id);
  if (!checklist) return { success: false, error: '점검표를 찾을 수 없습니다.' };
  const toggled = {
    ...checklist,
    status: checklist.status === '사용' ? '미사용' as const : '사용' as const,
  };
  return { success: true, data: toggled };
}

export async function reorderChecklists(
  _items: { id: string; order: number }[]
): Promise<{ success: boolean; error?: string }> {
  return { success: true };
}

export async function getChecklistStats(): Promise<{
  success: boolean;
  data?: { total: number; active: number; inactive: number };
  error?: string;
}> {
  const active = MOCK_CHECKLISTS.filter((c) => c.status === '사용').length;
  return {
    success: true,
    data: {
      total: MOCK_CHECKLISTS.length,
      active,
      inactive: MOCK_CHECKLISTS.length - active,
    },
  };
}

// ============================================================================
// 점검표 항목 CRUD
// ============================================================================

export async function getChecklistItems(_checklistId: string): Promise<{
  success: boolean;
  data?: ChecklistItem[];
  error?: string;
}> {
  return { success: true, data: [...MOCK_ITEMS] };
}

export async function getChecklistItemById(
  checklistId: string,
  itemId: string
): Promise<{ success: boolean; data?: ChecklistItem; error?: string }> {
  const item = MOCK_ITEMS.find((i) => i.id === itemId);
  if (!item) return { success: false, error: '항목을 찾을 수 없습니다.' };
  return { success: true, data: { ...item, documents: [...MOCK_DOCUMENTS] } };
}

export async function createChecklistItem(
  checklistId: string,
  data: ChecklistItemFormData
): Promise<{ success: boolean; data?: ChecklistItem; error?: string }> {
  const newItem: ChecklistItem = {
    id: `item-${Date.now()}`,
    checklistId,
    itemCode: String(Date.now()).slice(-6),
    itemName: data.itemName,
    description: data.description,
    documentCount: data.documents.length,
    status: data.status,
    order: MOCK_ITEMS.length + 1,
    documents: [],
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
  return { success: true, data: newItem };
}

export async function updateChecklistItem(
  checklistId: string,
  itemId: string,
  data: ChecklistItemFormData
): Promise<{ success: boolean; data?: ChecklistItem; error?: string }> {
  const item = MOCK_ITEMS.find((i) => i.id === itemId);
  if (!item) return { success: false, error: '항목을 찾을 수 없습니다.' };
  const updated = {
    ...item,
    itemName: data.itemName,
    description: data.description,
    status: data.status,
    updatedAt: new Date().toISOString(),
  };
  return { success: true, data: updated };
}

export async function deleteChecklistItem(
  _checklistId: string,
  _itemId: string
): Promise<{ success: boolean; error?: string }> {
  return { success: true };
}

export async function reorderChecklistItems(
  _checklistId: string,
  _items: { id: string; order: number }[]
): Promise<{ success: boolean; error?: string }> {
  return { success: true };
}