'use server';

import type { WorkerStatus, WorkerStatusStats } from './types';

// Mock 데이터 생성
const generateMockData = (): WorkerStatus[] => {
  const partners = ['현성엘리', '삼성전자', '대우건설', 'LG전자'];
  const sites = ['문정교회', '강남빌딩', '서초타워', '판교오피스'];
  const departments = ['시공', '설계', '관리', '영업'];
  const names = ['김정수', '김동혁', '이영희', '박철수', '최민수', '홍길동', '이순신', '강감찬'];
  const categories: ('foreman' | 'worker')[] = ['foreman', 'worker'];
  const statuses: ('absent' | 'checked_in' | 'checked_out' | 'early_leave' | 'other')[] = [
    'absent', 'checked_in', 'checked_out', 'early_leave', 'other'
  ];
  const contractStatuses: ('all_contract' | 'pending' | 'completed')[] = ['all_contract', 'pending', 'completed'];

  const mockData: WorkerStatus[] = [];

  for (let i = 1; i <= 30; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const hasCheckIn = status !== 'absent';
    const hasCheckOut = status === 'checked_out' || status === 'early_leave';

    mockData.push({
      id: `worker-${i}`,
      partnerName: partners[Math.floor(Math.random() * partners.length)],
      siteName: sites[Math.floor(Math.random() * sites.length)],
      category: categories[Math.floor(Math.random() * categories.length)],
      department: departments[Math.floor(Math.random() * departments.length)],
      workerName: names[Math.floor(Math.random() * names.length)],
      baseDate: `2025-09-${String(Math.floor(Math.random() * 30) + 1).padStart(2, '0')}`,
      checkInTime: hasCheckIn ? `${String(8 + Math.floor(Math.random() * 2)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}` : null,
      checkOutTime: hasCheckOut ? `${String(17 + Math.floor(Math.random() * 3)).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}` : null,
      constructionNumber: `CON-2025-${String(i).padStart(4, '0')}`,
      laborCost: (100000 + Math.floor(Math.random() * 100000)),
      status,
      contractStatus: contractStatuses[Math.floor(Math.random() * contractStatuses.length)],
      createdAt: new Date(2025, 8, i).toISOString(),
      updatedAt: new Date(2025, 8, i).toISOString(),
    });
  }

  return mockData;
};

interface GetWorkerStatusListParams {
  page?: number;
  size?: number;
  startDate?: string;
  endDate?: string;
}

interface GetWorkerStatusListResult {
  success: boolean;
  data?: {
    items: WorkerStatus[];
    totalItems: number;
    totalPages: number;
  };
  error?: string;
}

export async function getWorkerStatusList(
  params: GetWorkerStatusListParams = {}
): Promise<GetWorkerStatusListResult> {
  try {
    // Mock 데이터 반환
    const mockData = generateMockData();

    return {
      success: true,
      data: {
        items: mockData,
        totalItems: mockData.length,
        totalPages: Math.ceil(mockData.length / (params.size || 20)),
      },
    };
  } catch (error) {
    console.error('Failed to fetch worker status list:', error);
    return {
      success: false,
      error: '작업인력현황 목록을 불러오는데 실패했습니다.',
    };
  }
}

interface GetWorkerStatusStatsResult {
  success: boolean;
  data?: WorkerStatusStats;
  error?: string;
}

export async function getWorkerStatusStats(): Promise<GetWorkerStatusStatsResult> {
  // Mock 통계 데이터
  return {
    success: true,
    data: {
      allContract: 25,
      pending: 8,
      completed: 17,
    },
  };
}
