'use server';

/**
 * FQC (제품검사) 문서 시스템 Server Actions
 *
 * documents API를 활용한 FQC 문서 관리:
 * - POST /v1/documents/bulk-create-fqc  → 개소별 문서 일괄생성
 * - GET  /v1/documents/fqc-status       → 수주 FQC 진행현황
 * - GET  /v1/documents/{id}             → 문서 상세 조회
 * - POST /v1/documents/upsert           → 문서 데이터 저장
 * - GET  /v1/document-templates/{id}    → 양식 상세 조회
 */

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

// ===== API 응답 타입 =====

/** 양식 항목 */
interface TemplateItemApi {
  id: number;
  section_id: number;
  item_name: string;
  standard: string | null;
  tolerance: string | null;
  measurement_type: string;
  frequency: string;
  sort_order: number;
  category: string | null;
  method: string | null;
}

/** 양식 섹션 */
interface TemplateSectionApi {
  id: number;
  name: string;
  title: string | null;
  description: string | null;
  image_path: string | null;
  sort_order: number;
  items: TemplateItemApi[];
}

/** 양식 컬럼 */
interface TemplateColumnApi {
  id: number;
  label: string;
  column_type: string;
  width: string | null;
  group_name: string | null;
  sort_order: number;
}

/** 양식 결재라인 */
interface TemplateApprovalLineApi {
  id: number;
  name: string;
  department: string;
  sort_order: number;
}

/** 양식 기본필드 */
interface TemplateBasicFieldApi {
  id: number;
  label: string;
  field_key: string;
  field_type: string;
  default_value: string | null;
  is_required: boolean;
  sort_order: number;
}

/** 양식 상세 API 응답 */
interface DocumentTemplateApi {
  id: number;
  name: string;
  category: string;
  title: string | null;
  approval_lines: TemplateApprovalLineApi[];
  basic_fields: TemplateBasicFieldApi[];
  sections: TemplateSectionApi[];
  columns: TemplateColumnApi[];
}

/** 문서 데이터 (EAV) */
interface DocumentDataApi {
  id: number;
  document_id: number;
  section_id: number | null;
  column_id: number | null;
  row_index: number;
  field_key: string;
  field_value: string | null;
}

/** 문서 상세 API 응답 */
interface DocumentApi {
  id: number;
  template_id: number;
  document_no: string;
  title: string;
  status: string;
  linkable_type: string | null;
  linkable_id: number | null;
  created_by: number | null;
  updated_by: number | null;
  created_at: string;
  updated_at: string;
  template: DocumentTemplateApi;
  data: DocumentDataApi[];
}

/** FQC 일괄생성 응답 */
interface BulkCreateFqcResponse {
  created_count: number;
  skipped_count: number;
  total_items: number;
  documents: Array<{
    id: number;
    document_no: string;
    title: string;
    status: string;
    linkable_id: number;
  }>;
}

/** FQC 진행현황 항목 */
interface FqcStatusItemApi {
  order_item_id: number;
  floor_code: string;
  symbol_code: string;
  specification: string;
  item_name: string;
  document_id: number | null;
  document_no: string | null;
  status: string;
  judgement: string | null;
}

/** FQC 진행현황 응답 */
interface FqcStatusResponse {
  order_id: number;
  order_no: string;
  total: number;
  created: number;
  approved: number;
  passed: number;
  failed: number;
  pending: number;
  items: FqcStatusItemApi[];
}

// ===== Frontend 타입 =====

export interface FqcTemplateItem {
  id: number;
  sectionId: number;
  itemName: string;
  standard: string | null;
  tolerance: string | null;
  measurementType: string;
  frequency: string;
  sortOrder: number;
  category: string;
  method: string;
}

export interface FqcTemplateSection {
  id: number;
  name: string;
  title: string | null;
  description: string | null;
  imagePath: string | null;
  sortOrder: number;
  items: FqcTemplateItem[];
}

export interface FqcTemplateColumn {
  id: number;
  label: string;
  columnType: string;
  width: string | null;
  groupName: string | null;
  sortOrder: number;
}

export interface FqcApprovalLine {
  id: number;
  name: string;
  department: string;
  sortOrder: number;
}

export interface FqcBasicField {
  id: number;
  label: string;
  fieldKey: string;
  fieldType: string;
  defaultValue: string | null;
  isRequired: boolean;
  sortOrder: number;
}

export interface FqcTemplate {
  id: number;
  name: string;
  category: string;
  title: string | null;
  approvalLines: FqcApprovalLine[];
  basicFields: FqcBasicField[];
  sections: FqcTemplateSection[];
  columns: FqcTemplateColumn[];
}

export interface FqcDocumentData {
  sectionId: number | null;
  columnId: number | null;
  rowIndex: number;
  fieldKey: string;
  fieldValue: string | null;
}

export interface FqcDocument {
  id: number;
  templateId: number;
  documentNo: string;
  title: string;
  status: string;
  linkableId: number | null;
  createdAt: string;
  template: FqcTemplate;
  data: FqcDocumentData[];
}

export interface FqcStatusItem {
  orderItemId: number;
  floorCode: string;
  symbolCode: string;
  specification: string;
  itemName: string;
  documentId: number | null;
  documentNo: string | null;
  status: string;
  judgement: string | null;
}

export interface FqcStatus {
  orderId: number;
  orderNo: string;
  total: number;
  created: number;
  approved: number;
  passed: number;
  failed: number;
  pending: number;
  items: FqcStatusItem[];
}

// ===== 변환 함수 =====

function transformTemplate(api: DocumentTemplateApi): FqcTemplate {
  return {
    id: api.id,
    name: api.name,
    category: api.category,
    title: api.title,
    approvalLines: (api.approval_lines || []).map(al => ({
      id: al.id,
      name: al.name,
      department: al.department,
      sortOrder: al.sort_order,
    })),
    basicFields: (api.basic_fields || []).map(bf => ({
      id: bf.id,
      label: bf.label,
      fieldKey: bf.field_key,
      fieldType: bf.field_type,
      defaultValue: bf.default_value,
      isRequired: bf.is_required,
      sortOrder: bf.sort_order,
    })),
    sections: (api.sections || []).map(s => ({
      id: s.id,
      name: s.name,
      title: s.title,
      description: s.description ?? null,
      imagePath: s.image_path,
      sortOrder: s.sort_order,
      items: (s.items || []).map(item => ({
        id: item.id,
        sectionId: item.section_id,
        itemName: item.item_name,
        standard: item.standard,
        tolerance: item.tolerance,
        measurementType: item.measurement_type,
        frequency: item.frequency,
        sortOrder: item.sort_order,
        category: item.category || '',
        method: item.method || '',
      })),
    })),
    columns: (api.columns || []).map(c => ({
      id: c.id,
      label: c.label,
      columnType: c.column_type,
      width: c.width,
      groupName: c.group_name ?? null,
      sortOrder: c.sort_order,
    })),
  };
}

function transformDocument(api: DocumentApi): FqcDocument {
  return {
    id: api.id,
    templateId: api.template_id,
    documentNo: api.document_no,
    title: api.title,
    status: api.status,
    linkableId: api.linkable_id,
    createdAt: api.created_at,
    template: transformTemplate(api.template),
    data: (api.data || []).map(d => ({
      sectionId: d.section_id,
      columnId: d.column_id,
      rowIndex: d.row_index,
      fieldKey: d.field_key,
      fieldValue: d.field_value,
    })),
  };
}

function transformFqcStatus(api: FqcStatusResponse): FqcStatus {
  return {
    orderId: api.order_id,
    orderNo: api.order_no,
    total: api.total,
    created: api.created,
    approved: api.approved,
    passed: api.passed,
    failed: api.failed,
    pending: api.pending,
    items: api.items.map(item => ({
      orderItemId: item.order_item_id,
      floorCode: item.floor_code,
      symbolCode: item.symbol_code,
      specification: item.specification,
      itemName: item.item_name,
      documentId: item.document_id,
      documentNo: item.document_no,
      status: item.status,
      judgement: item.judgement,
    })),
  };
}

// ===== Server Actions =====

const FQC_TEMPLATE_ID = 65;
const FQC_REQUEST_TEMPLATE_ID = 66;

/**
 * FQC 양식 상세 조회
 * GET /v1/document-templates/{id}
 */
export async function getFqcTemplate(): Promise<{
  success: boolean;
  data?: FqcTemplate;
  error?: string;
  __authError?: boolean;
}> {
  return executeServerAction<DocumentTemplateApi, FqcTemplate>({
    url: buildApiUrl(`/api/v1/document-templates/${FQC_TEMPLATE_ID}`),
    transform: transformTemplate,
    errorMessage: 'FQC 양식 조회에 실패했습니다.',
  });
}

/**
 * 제품검사 요청서 양식 상세 조회
 * GET /v1/document-templates/{id}
 */
export async function getFqcRequestTemplate(): Promise<{
  success: boolean;
  data?: FqcTemplate;
  error?: string;
  __authError?: boolean;
}> {
  return executeServerAction<DocumentTemplateApi, FqcTemplate>({
    url: buildApiUrl(`/api/v1/document-templates/${FQC_REQUEST_TEMPLATE_ID}`),
    transform: transformTemplate,
    errorMessage: '제품검사 요청서 양식 조회에 실패했습니다.',
  });
}

/**
 * FQC 문서 일괄생성
 * POST /v1/documents/bulk-create-fqc
 */
export async function bulkCreateFqcDocuments(orderId: number): Promise<{
  success: boolean;
  data?: BulkCreateFqcResponse;
  error?: string;
  __authError?: boolean;
}> {
  return executeServerAction<BulkCreateFqcResponse>({
    url: buildApiUrl('/api/v1/documents/bulk-create-fqc'),
    method: 'POST',
    body: {
      template_id: FQC_TEMPLATE_ID,
      order_id: orderId,
    },
    errorMessage: 'FQC 문서 일괄생성에 실패했습니다.',
  });
}

/**
 * FQC 진행현황 조회
 * GET /v1/documents/fqc-status?order_id=N&template_id=65
 */
export async function getFqcStatus(orderId: number): Promise<{
  success: boolean;
  data?: FqcStatus;
  error?: string;
  __authError?: boolean;
}> {
  return executeServerAction<FqcStatusResponse, FqcStatus>({
    url: buildApiUrl('/api/v1/documents/fqc-status', {
      order_id: orderId,
      template_id: FQC_TEMPLATE_ID,
    }),
    transform: transformFqcStatus,
    errorMessage: 'FQC 진행현황 조회에 실패했습니다.',
  });
}

/**
 * FQC 문서 상세 조회
 * GET /v1/documents/{id}
 */
export async function getFqcDocument(documentId: number): Promise<{
  success: boolean;
  data?: FqcDocument;
  error?: string;
  __authError?: boolean;
}> {
  return executeServerAction<DocumentApi, FqcDocument>({
    url: buildApiUrl(`/api/v1/documents/${documentId}`),
    transform: transformDocument,
    errorMessage: 'FQC 문서 조회에 실패했습니다.',
  });
}

/**
 * FQC 문서 데이터 저장 (upsert)
 * POST /v1/documents/upsert
 */
export async function saveFqcDocument(params: {
  documentId?: number;
  templateId?: number;
  itemId?: number;
  title?: string;
  renderedHtml?: string;
  data: Array<{
    section_id?: number | null;
    column_id?: number | null;
    row_index: number;
    field_key: string;
    field_value: string | null;
  }>;
}): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  const body: Record<string, unknown> = {
    template_id: params.templateId ?? FQC_TEMPLATE_ID,
    data: params.data,
  };

  if (params.documentId) body.document_id = params.documentId;
  if (params.itemId) body.item_id = params.itemId;
  if (params.title) body.title = params.title;
  if (params.renderedHtml) body.rendered_html = params.renderedHtml;

  return executeServerAction({
    url: buildApiUrl('/api/v1/documents/upsert'),
    method: 'POST',
    body,
    errorMessage: 'FQC 검사 데이터 저장에 실패했습니다.',
  });
}

/**
 * 문서 rendered_html 스냅샷 저장 (Lazy Snapshot)
 * PATCH /v1/documents/{id}/snapshot
 */
export async function patchDocumentSnapshot(
  documentId: number,
  renderedHtml: string,
): Promise<{ success: boolean; error?: string }> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/documents/${documentId}/snapshot`),
    method: 'PATCH',
    body: { rendered_html: renderedHtml },
    errorMessage: '스냅샷 저장에 실패했습니다.',
  });
}