'use server';

import type { Utility, UtilityStats, UtilityStatus } from './types';
import { format, addDays, subDays, subMonths } from 'date-fns';

/**
 * 목업 공과 데이터 생성 (고정 데이터)
 */
function generateMockUtilities(): Utility[] {
  // types.ts MOCK_PARTNERS와 일치
  const partners = [
    { id: '1', name: '(주)대한건설' },
    { id: '2', name: '삼성물산' },
    { id: '3', name: '현대건설' },
    { id: '4', name: 'GS건설' },
    { id: '5', name: '대림산업' },
  ];

  // types.ts MOCK_SITES와 일치
  const sites = [
    { id: '1', name: '강남 오피스빌딩 신축' },
    { id: '2', name: '판교 데이터센터' },
    { id: '3', name: '송도 물류센터' },
    { id: '4', name: '인천공항 터미널' },
    { id: '5', name: '부산항 창고' },
  ];

  // types.ts MOCK_CONSTRUCTION_PM과 일치
  const constructionPMs = [
    { id: '1', name: '홍길동' },
    { id: '2', name: '김철수' },
    { id: '3', name: '이영희' },
    { id: '4', name: '박민수' },
  ];

  // types.ts MOCK_UTILITY_TYPES와 일치
  const utilityTypes = ['전기공과', '수도공과', '가스공과', '통신공과', '난방공과'];

  // types.ts MOCK_WORK_TEAM_LEADERS와 일치
  const workTeamLeaders = [
    { id: '1', name: '이반장' },
    { id: '2', name: '김반장' },
    { id: '3', name: '박반장' },
    { id: '4', name: '최반장' },
  ];

  const statuses: UtilityStatus[] = ['scheduled', 'issued', 'completed', 'expired'];

  const utilities: Utility[] = [];
  // 고정 기준일 (2026-01-06)
  const baseDate = new Date(2026, 0, 6);

  for (let i = 0; i < 50; i++) {
    const partner = partners[i % partners.length];
    const site = sites[i % sites.length];
    const pm = constructionPMs[i % constructionPMs.length];
    const workTeamLeader = workTeamLeaders[i % workTeamLeaders.length];
    const status = statuses[i % statuses.length];
    const utilityType = utilityTypes[i % utilityTypes.length];

    // 날짜도 index 기반으로 고정
    const monthOffset = i % 3;
    const dayOffset = (i * 3) % 30;
    const periodStart = subMonths(addDays(baseDate, -dayOffset), monthOffset);
    const periodEnd = addDays(periodStart, 10 + (i % 20));
    const scheduledDate = addDays(periodStart, i % 5);
    const constructionStartDate = addDays(periodStart, i % 7);

    utilities.push({
      id: `utility-${i + 1}`,
      utilityNumber: `UTL-${2026}-${String(i + 1).padStart(4, '0')}`,
      partnerId: partner.id,
      partnerName: partner.name,
      siteId: site.id,
      siteName: site.name,
      constructionPMId: pm.id,
      constructionPM: pm.name,
      utilityType,
      scheduledDate: format(scheduledDate, 'yyyy-MM-dd'),
      amount: 100000 + (i * 50000) % 900000, // 100,000 ~ 1,000,000 고정 패턴
      workTeamLeaderId: workTeamLeader.id,
      workTeamLeader: workTeamLeader.name,
      constructionStartDate: format(constructionStartDate, 'yyyy-MM-dd'),
      status,
      periodStart: format(periodStart, 'yyyy-MM-dd'),
      periodEnd: format(periodEnd, 'yyyy-MM-dd'),
      createdAt: format(subDays(periodStart, i % 10), 'yyyy-MM-dd\'T\'HH:mm:ss'),
      updatedAt: format(baseDate, 'yyyy-MM-dd\'T\'HH:mm:ss'),
    });
  }

  return utilities;
}

// 캐시된 목업 데이터
let cachedUtilities: Utility[] | null = null;

function getMockUtilities(): Utility[] {
  if (!cachedUtilities) {
    cachedUtilities = generateMockUtilities();
  }
  return cachedUtilities;
}

/**
 * 공과 목록 조회
 */
export async function getUtilityList(params?: {
  size?: number;
  page?: number;
  startDate?: string;
  endDate?: string;
  status?: string;
  partnerId?: string;
  search?: string;
}): Promise<{
  success: boolean;
  data?: { items: Utility[]; total: number };
  error?: string;
}> {
  try {
    let utilities = getMockUtilities();

    // 날짜 필터
    if (params?.startDate && params?.endDate) {
      utilities = utilities.filter((utility) => {
        return utility.periodStart >= params.startDate! && utility.periodEnd <= params.endDate!;
      });
    }

    // 상태 필터
    if (params?.status && params.status !== 'all') {
      utilities = utilities.filter((utility) => utility.status === params.status);
    }

    // 거래처 필터
    if (params?.partnerId && params.partnerId !== 'all') {
      utilities = utilities.filter((utility) => utility.partnerId === params.partnerId);
    }

    // 검색
    if (params?.search) {
      const search = params.search.toLowerCase();
      utilities = utilities.filter(
        (utility) =>
          utility.utilityNumber.toLowerCase().includes(search) ||
          utility.partnerName.toLowerCase().includes(search) ||
          utility.siteName.toLowerCase().includes(search) ||
          utility.constructionPM.toLowerCase().includes(search)
      );
    }

    // 페이지네이션
    const page = params?.page || 1;
    const size = params?.size || 1000;
    const start = (page - 1) * size;
    const paginatedUtilities = utilities.slice(start, start + size);

    return {
      success: true,
      data: {
        items: paginatedUtilities,
        total: utilities.length,
      },
    };
  } catch {
    return {
      success: false,
      error: '공과 목록 조회에 실패했습니다.',
    };
  }
}

/**
 * 공과 통계 조회 (상단 카드용)
 */
export async function getUtilityStats(): Promise<{
  success: boolean;
  data?: UtilityStats;
  error?: string;
}> {
  try {
    const utilities = getMockUtilities();

    // 상단 카드: 전체 계약, 계약 대기, 계약 완료
    const stats: UtilityStats = {
      totalContract: utilities.length,
      contractWaiting: utilities.filter((u) => u.status === 'scheduled' || u.status === 'issued').length,
      contractComplete: utilities.filter((u) => u.status === 'completed').length,
    };

    return {
      success: true,
      data: stats,
    };
  } catch {
    return {
      success: false,
      error: '공과 통계 조회에 실패했습니다.',
    };
  }
}

/**
 * 공과 삭제
 */
export async function deleteUtility(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    if (cachedUtilities) {
      cachedUtilities = cachedUtilities.filter((u) => u.id !== id);
    }

    return { success: true };
  } catch {
    return {
      success: false,
      error: '공과 삭제에 실패했습니다.',
    };
  }
}

/**
 * 공과 일괄 삭제
 */
export async function deleteUtilities(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    if (cachedUtilities) {
      const beforeCount = cachedUtilities.length;
      cachedUtilities = cachedUtilities.filter((u) => !ids.includes(u.id));
      const deletedCount = beforeCount - cachedUtilities.length;

      return {
        success: true,
        deletedCount,
      };
    }

    return {
      success: true,
      deletedCount: ids.length,
    };
  } catch {
    return {
      success: false,
      error: '공과 일괄 삭제에 실패했습니다.',
    };
  }
}

/**
 * 공과 상세 조회
 */
export async function getUtilityDetail(id: string): Promise<{
  success: boolean;
  data?: Utility;
  error?: string;
}> {
  try {
    const utilities = getMockUtilities();
    const utility = utilities.find((u) => u.id === id);

    if (!utility) {
      return {
        success: false,
        error: '공과를 찾을 수 없습니다.',
      };
    }

    return {
      success: true,
      data: utility,
    };
  } catch {
    return {
      success: false,
      error: '공과 상세 조회에 실패했습니다.',
    };
  }
}