'use server';

/**
 * 실적신고관리 Server Actions
 *
 * API Endpoints:
 * - GET /api/v1/quality/performance-reports - 분기별 실적신고 목록
 * - GET /api/v1/quality/performance-reports/stats - 통계
 * - GET /api/v1/quality/performance-reports/missing - 누락체크 목록
 * - GET /api/v1/quality/performance-reports/export-excel - 확정건 엑셀 다운로드
 * - PATCH /api/v1/quality/performance-reports/confirm - 선택 확정
 * - PATCH /api/v1/quality/performance-reports/unconfirm - 확정 해제
 * - PATCH /api/v1/quality/performance-reports/memo - 메모 일괄 적용
 */

import { executeServerAction } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import { cookies } from 'next/headers';
import type {
  PerformanceReport,
  PerformanceReportStats,
  MissedReport,
  Quarter,
} from './types';
import {
  mockPerformanceReports,
  mockPerformanceReportStats,
  mockMissedReports,
} from './mockData';

// 개발환경 Mock 데이터 fallback 플래그
const USE_MOCK_FALLBACK = false;

// ===== API 응답 → 프론트 타입 변환 =====

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function transformReport(item: any): PerformanceReport {
  return {
    id: String(item.id ?? ''),
    qualityDocNumber: item.quality_doc_number ?? '',
    createdDate: item.created_date ?? '',
    siteName: item.site_name ?? '',
    client: item.client ?? '',
    locationCount: item.location_count ?? 0,
    requiredInfo: item.required_info ?? '',
    confirmStatus: item.confirm_status === 'confirmed' ? '확정' : '미확정',
    confirmDate: item.confirm_date ?? '',
    memo: item.memo ?? '',
    year: item.year ?? new Date().getFullYear(),
    quarter: item.quarter ?? 'Q1',
  };
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function transformStats(item: any): PerformanceReportStats {
  return {
    totalCount: item.total_count ?? 0,
    confirmedCount: item.confirmed_count ?? 0,
    unconfirmedCount: item.unconfirmed_count ?? 0,
    totalLocations: item.total_locations ?? 0,
  };
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function transformMissedReport(item: any): MissedReport {
  return {
    id: String(item.id ?? ''),
    qualityDocNumber: item.quality_doc_number ?? item.order_number ?? '',
    siteName: item.site_name ?? '',
    client: item.client ?? '',
    locationCount: item.location_count ?? 0,
    inspectionCompleteDate: item.delivery_date ?? '',
    memo: item.memo ?? '',
  };
}

// ===== 페이지네이션 =====

interface PaginationMeta {
  currentPage: number;
  lastPage: number;
  perPage: number;
  total: number;
}

// ===== 분기별 실적신고 목록 조회 =====

export async function getPerformanceReports(params?: {
  page?: number;
  size?: number;
  q?: string;
  year?: number;
  quarter?: Quarter | '전체';
}): Promise<{
  success: boolean;
  data: PerformanceReport[];
  pagination: PaginationMeta;
  error?: string;
  __authError?: boolean;
}> {
  const defaultPagination = { currentPage: 1, lastPage: 1, perPage: 20, total: 0 };

  interface ApiListData { items?: PerformanceReport[]; current_page?: number; last_page?: number; per_page?: number; total?: number }
  const result = await executeServerAction<ApiListData>({
    url: buildApiUrl('/api/v1/quality/performance-reports', {
      page: params?.page,
      per_page: params?.size,
      q: params?.q,
      year: params?.year,
      quarter: params?.quarter && params.quarter !== '전체' ? params.quarter : undefined,
    }),
    errorMessage: '실적신고 목록 조회에 실패했습니다.',
  });

  if (!result.success) {
    if (USE_MOCK_FALLBACK) {
      let filtered = [...mockPerformanceReports];
      if (params?.year) filtered = filtered.filter(i => i.year === params.year);
      if (params?.quarter && params.quarter !== '전체') filtered = filtered.filter(i => i.quarter === params.quarter);
      if (params?.q) {
        const q = params.q.toLowerCase();
        filtered = filtered.filter(i =>
          i.siteName.toLowerCase().includes(q) || i.client.toLowerCase().includes(q) || i.qualityDocNumber.toLowerCase().includes(q)
        );
      }
      const page = params?.page || 1;
      const size = params?.size || 20;
      const start = (page - 1) * size;
      return {
        success: true,
        data: filtered.slice(start, start + size),
        pagination: { currentPage: page, lastPage: Math.ceil(filtered.length / size), perPage: size, total: filtered.length },
      };
    }
    return { success: false, data: [], pagination: defaultPagination, error: result.error, __authError: result.__authError };
  }

  const d = result.data;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const items = (d?.items || []).map((item: any) => transformReport(item));
  return {
    success: true,
    data: items,
    pagination: {
      currentPage: d?.current_page || 1,
      lastPage: d?.last_page || 1,
      perPage: d?.per_page || 20,
      total: d?.total || 0,
    },
  };
}

// ===== 통계 조회 =====

export async function getPerformanceReportStats(params?: {
  year?: number;
  quarter?: Quarter | '전체';
}): Promise<{
  success: boolean;
  data?: PerformanceReportStats;
  error?: string;
  __authError?: boolean;
}> {
  const result = await executeServerAction<PerformanceReportStats>({
    url: buildApiUrl('/api/v1/quality/performance-reports/stats', {
      year: params?.year,
      quarter: params?.quarter && params.quarter !== '전체' ? params.quarter : undefined,
    }),
    errorMessage: '실적신고 통계 조회에 실패했습니다.',
  });

  if (!result.success) {
    if (USE_MOCK_FALLBACK) return { success: true, data: mockPerformanceReportStats };
    return { success: false, error: result.error, __authError: result.__authError };
  }
  return { success: true, data: result.data ? transformStats(result.data) : undefined };
}

// ===== 누락체크 목록 조회 =====

export async function getMissedReports(params?: {
  page?: number;
  size?: number;
  q?: string;
}): Promise<{
  success: boolean;
  data: MissedReport[];
  pagination: PaginationMeta;
  error?: string;
  __authError?: boolean;
}> {
  const defaultPagination = { currentPage: 1, lastPage: 1, perPage: 20, total: 0 };

  interface ApiMissedData { items?: MissedReport[]; current_page?: number; last_page?: number; per_page?: number; total?: number }
  const result = await executeServerAction<ApiMissedData>({
    url: buildApiUrl('/api/v1/quality/performance-reports/missing', {
      page: params?.page,
      per_page: params?.size,
      q: params?.q,
    }),
    errorMessage: '누락체크 목록 조회에 실패했습니다.',
  });

  if (!result.success) {
    if (USE_MOCK_FALLBACK) {
      let filtered = [...mockMissedReports];
      if (params?.q) {
        const q = params.q.toLowerCase();
        filtered = filtered.filter(i =>
          i.siteName.toLowerCase().includes(q) || i.client.toLowerCase().includes(q) || i.qualityDocNumber.toLowerCase().includes(q)
        );
      }
      const page = params?.page || 1;
      const size = params?.size || 20;
      const start = (page - 1) * size;
      return {
        success: true,
        data: filtered.slice(start, start + size),
        pagination: { currentPage: page, lastPage: Math.ceil(filtered.length / size), perPage: size, total: filtered.length },
      };
    }
    return { success: false, data: [], pagination: defaultPagination, error: result.error, __authError: result.__authError };
  }

  const d = result.data;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const items = (d?.items || []).map((item: any) => transformMissedReport(item));
  return {
    success: true,
    data: items,
    pagination: {
      currentPage: d?.current_page || 1,
      lastPage: d?.last_page || 1,
      perPage: d?.per_page || 20,
      total: d?.total || 0,
    },
  };
}

// ===== 선택 확정 =====

export async function confirmReports(ids: string[]): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/quality/performance-reports/confirm'),
    method: 'PATCH',
    body: { ids },
    errorMessage: '확정 처리에 실패했습니다.',
  });
  if (!result.success && USE_MOCK_FALLBACK) return { success: true };
  return { success: result.success, error: result.error, __authError: result.__authError };
}

// ===== 확정 해제 =====

export async function unconfirmReports(ids: string[]): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/quality/performance-reports/unconfirm'),
    method: 'PATCH',
    body: { ids },
    errorMessage: '확정 해제에 실패했습니다.',
  });
  if (!result.success && USE_MOCK_FALLBACK) return { success: true };
  return { success: result.success, error: result.error, __authError: result.__authError };
}

// ===== 배포 (TODO: 백엔드 API 미구현 - 추후 추가 예정) =====

export async function distributeReports(ids: string[]): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/quality/performance-reports/distribute'),
    method: 'POST',
    body: { ids },
    errorMessage: '배포에 실패했습니다.',
  });
  return { success: result.success, error: result.error, __authError: result.__authError };
}

// ===== 메모 일괄 적용 =====

export async function updateMemo(ids: string[], memo: string): Promise<{
  success: boolean;
  error?: string;
  __authError?: boolean;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/quality/performance-reports/memo'),
    method: 'PATCH',
    body: { ids, memo },
    errorMessage: '메모 저장에 실패했습니다.',
  });
  if (!result.success && USE_MOCK_FALLBACK) return { success: true };
  return { success: result.success, error: result.error, __authError: result.__authError };
}

// ===== 확정건 엑셀 다운로드 =====

export async function exportConfirmedExcel(params: {
  year: number;
  quarter: number;
}): Promise<{
  success: boolean;
  data?: Blob;
  filename?: string;
  error?: string;
}> {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('access_token')?.value;

    const headers: HeadersInit = {
      'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Authorization': token ? `Bearer ${token}` : '',
      'X-API-KEY': process.env.API_KEY || '',
    };

    const url = buildApiUrl('/api/v1/quality/performance-reports/export-excel', {
      year: params.year,
      quarter: params.quarter,
    });

    const response = await fetch(url, { method: 'GET', headers });

    if (!response.ok) {
      return { success: false, error: `API 오류: ${response.status}` };
    }

    const blob = await response.blob();
    const contentDisposition = response.headers.get('Content-Disposition');
    const filenameMatch = contentDisposition?.match(/filename\*?=(?:UTF-8'')?(.+)/);
    const filename = filenameMatch?.[1]
      ? decodeURIComponent(filenameMatch[1])
      : `판매실적대장_${params.year}년_${params.quarter}분기.xlsx`;

    return { success: true, data: blob, filename };
  } catch (error) {
    if (error instanceof Error && error.message?.includes('NEXT_REDIRECT')) throw error;
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}
