'use server';

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

// ===== API 원본 타입 (snake_case) =====
// ⚠️ 'use server' 파일에서 타입 re-export 금지 (Turbopack 제한)

interface QualityReportApi {
  id: number;
  code: string;
  site_name: string;
  item: string;
  route_count: number;
  total_routes: number;
  quarter: string;
  year: number;
  quarter_num: number;
}

interface RouteItemApi {
  id: number;
  code: string;
  date: string;
  client: string;
  site: string;
  location_count: number;
  sub_items: {
    id: number;
    name: string;
    location: string;
    is_completed: boolean;
  }[];
}

interface DocumentApi {
  id: number;
  type: string;
  title: string;
  date?: string;
  count: number;
  file_id?: number;
  file_name?: string;
  file_size?: number;
  items?: {
    id: number;
    title: string;
    date: string;
    code?: string;
    sub_type?: string;
    work_order_id?: number;
  }[];
}

// ===== Transform 함수 (snake_case → camelCase) =====

function transformReportApi(api: QualityReportApi) {
  return {
    id: String(api.id),
    code: api.code,
    siteName: api.site_name,
    item: api.item,
    routeCount: api.route_count,
    totalRoutes: api.total_routes,
    quarter: api.quarter,
    year: api.year,
    quarterNum: api.quarter_num,
  };
}

function transformRouteApi(api: RouteItemApi) {
  return {
    id: String(api.id),
    code: api.code,
    date: api.date,
    client: api.client,
    site: api.site,
    locationCount: api.location_count,
    subItems: api.sub_items.map((s) => ({
      id: String(s.id),
      name: s.name,
      location: s.location,
      isCompleted: s.is_completed,
    })),
  };
}

function transformDocumentApi(api: DocumentApi) {
  return {
    id: String(api.id),
    type: api.type as 'import' | 'order' | 'log' | 'report' | 'confirmation' | 'shipping' | 'product' | 'quality',
    title: api.title,
    date: api.date,
    count: api.count,
    fileId: api.file_id,
    fileName: api.file_name,
    fileSize: api.file_size,
    items: api.items?.map((i) => ({
      id: String(i.id),
      title: i.title,
      date: i.date,
      code: i.code,
      subType: i.sub_type as 'screen' | 'bending' | 'slat' | 'jointbar' | undefined,
      workOrderId: i.work_order_id,
    })),
  };
}

// ===== 2일차: 로트 추적 심사 =====

export async function getQualityReports(params: {
  year: number;
  quarter?: number;
  q?: string;
}) {
  return executeServerAction({
    url: buildApiUrl('/api/v1/qms/lot-audit/reports', {
      year: params.year,
      quarter: params.quarter,
      q: params.q,
    }),
    transform: (data: { items: QualityReportApi[] }) =>
      data.items.map(transformReportApi),
    errorMessage: '품질관리서 목록 조회에 실패했습니다.',
  });
}

export async function getReportRoutes(reportId: string) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/qms/lot-audit/reports/${reportId}`),
    transform: (data: RouteItemApi[]) => data.map(transformRouteApi),
    errorMessage: '수주/개소 목록 조회에 실패했습니다.',
  });
}

export async function getRouteDocuments(routeId: string) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/qms/lot-audit/routes/${routeId}/documents`),
    transform: (data: DocumentApi[]) => data.map(transformDocumentApi),
    errorMessage: '서류 목록 조회에 실패했습니다.',
  });
}

export async function getDocumentDetail(type: string, id: string) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/qms/lot-audit/documents/${type}/${id}`),
    errorMessage: '서류 상세 조회에 실패했습니다.',
  });
}

export async function confirmUnitInspection(unitId: string, confirmed: boolean) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/qms/lot-audit/units/${unitId}/confirm`),
    method: 'PATCH',
    body: { confirmed },
    transform: (data: { id: number; name: string; location: string; is_completed: boolean }) => ({
      id: String(data.id),
      name: data.name,
      location: data.location,
      isCompleted: data.is_completed,
    }),
    errorMessage: '확인 상태 변경에 실패했습니다.',
  });
}

// ===== 1일차: 점검표 항목 토글 =====

export async function toggleTemplateItem(templateId: number, subItemId: string) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/quality/checklist-templates/${templateId}/items/${subItemId}/toggle`),
    method: 'PATCH',
    transform: (data: { id: string; name: string; is_completed: boolean; completed_at?: string }) => ({
      id: data.id,
      name: data.name,
      isCompleted: data.is_completed,
    }),
    errorMessage: '항목 상태 변경에 실패했습니다.',
  });
}

// ===== 점검표 템플릿 관리 (설정 모달) =====

interface ChecklistTemplateApi {
  id: number;
  name: string;
  type: string;
  categories: {
    id: string;
    title: string;
    subItems: { id: string; name: string; is_completed?: boolean }[];
  }[];
  options: Record<string, unknown> | null;
  file_counts: Record<string, number>;
  updated_at: string | null;
  updated_by: string | null;
}

interface TemplateDocumentApi {
  id: number;
  field_key: string;
  display_name: string;
  file_size: number;
  mime_type: string;
  uploaded_by: string | null;
  created_at: string | null;
}

export async function getChecklistTemplate(type: string = 'day1_audit') {
  return executeServerAction({
    url: buildApiUrl('/api/v1/quality/checklist-templates', { type }),
    transform: (data: ChecklistTemplateApi) => ({
      id: data.id,
      name: data.name,
      type: data.type,
      categories: data.categories.map((cat) => ({
        id: cat.id,
        title: cat.title,
        subItems: cat.subItems.map((item) => ({
          id: item.id,
          name: item.name,
          isCompleted: item.is_completed ?? false,
        })),
      })),
      options: data.options,
      fileCounts: data.file_counts,
      updatedAt: data.updated_at,
      updatedBy: data.updated_by,
    }),
    errorMessage: '점검표 템플릿 조회에 실패했습니다.',
  });
}

export async function saveChecklistTemplate(
  id: number,
  data: { name?: string; categories: { id: string; title: string; subItems: { id: string; name: string }[] }[]; options?: Record<string, unknown> },
) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/quality/checklist-templates/${id}`),
    method: 'PUT',
    body: data,
    transform: (result: ChecklistTemplateApi) => ({
      id: result.id,
      name: result.name,
      type: result.type,
      categories: result.categories.map((cat) => ({
        id: cat.id,
        title: cat.title,
        subItems: cat.subItems.map((item) => ({
          id: item.id,
          name: item.name,
          isCompleted: item.is_completed ?? false,
        })),
      })),
      options: result.options,
      fileCounts: result.file_counts,
      updatedAt: result.updated_at,
      updatedBy: result.updated_by,
    }),
    errorMessage: '점검표 템플릿 저장에 실패했습니다.',
  });
}

export async function getTemplateDocuments(templateId: number, subItemId?: string) {
  return executeServerAction({
    url: buildApiUrl('/api/v1/quality/qms-documents', {
      template_id: templateId,
      sub_item_id: subItemId,
    }),
    transform: (data: TemplateDocumentApi[]) =>
      data.map((d) => ({
        id: d.id,
        fieldKey: d.field_key,
        displayName: d.display_name,
        fileSize: d.file_size,
        mimeType: d.mime_type,
        uploadedBy: d.uploaded_by,
        createdAt: d.created_at,
      })),
    errorMessage: '템플릿 문서 조회에 실패했습니다.',
  });
}

export async function uploadTemplateDocument(templateId: number, subItemId: string, file: File) {
  const formData = new FormData();
  formData.append('template_id', String(templateId));
  formData.append('sub_item_id', subItemId);
  formData.append('file', file);

  return executeServerAction({
    url: buildApiUrl('/api/v1/quality/qms-documents'),
    method: 'POST',
    body: formData,
    transform: (d: TemplateDocumentApi) => ({
      id: d.id,
      fieldKey: d.field_key,
      displayName: d.display_name,
      fileSize: d.file_size,
      mimeType: d.mime_type,
      createdAt: d.created_at,
    }),
    errorMessage: '파일 업로드에 실패했습니다.',
  });
}

export async function deleteTemplateDocument(fileId: number, replace: boolean = false) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/quality/qms-documents/${fileId}`, {
      replace: replace ? 'true' : undefined,
    }),
    method: 'DELETE',
    errorMessage: '파일 삭제에 실패했습니다.',
  });
}

// ===== 품질관리서 파일 업로드/삭제 =====

export async function uploadQualityDocumentFile(qualityDocumentId: string, file: File) {
  const formData = new FormData();
  formData.append('file', file);

  return executeServerAction({
    url: buildApiUrl(`/api/v1/quality/documents/${qualityDocumentId}/upload-file`),
    method: 'POST',
    body: formData,
    transform: (data: { id: number; display_name: string; file_size: number }) => ({
      fileId: data.id,
      fileName: data.display_name,
      fileSize: data.file_size,
    }),
    errorMessage: '품질관리서 파일 업로드에 실패했습니다.',
  });
}

export async function deleteQualityDocumentFile(qualityDocumentId: string) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/quality/documents/${qualityDocumentId}/file`),
    method: 'DELETE',
    errorMessage: '품질관리서 파일 삭제에 실패했습니다.',
  });
}
