'use server';

import type { Site, SiteStats, SiteStatus } from './types';
import { apiClient } from '@/lib/api';

/**
 * 주일 기업 - 현장관리 Server Actions
 * 표준화된 apiClient 사용 버전
 */

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

interface ApiSite {
  id: number;
  site_code: string | null;
  client_id: number | null;
  name: string;
  address: string | null;
  status: SiteStatus;
  created_at: string;
  updated_at: string;
  client?: {
    id: number;
    name: string;
  } | null;
}

interface ApiSiteStats {
  total: number;
  construction: number;
  unregistered: number;
  suspended: number;
  pending: number;
}

// ========================================
// 타입 변환 함수
// ========================================

/**
 * API 응답 → Site 타입 변환
 */
function transformSite(apiData: ApiSite): Site {
  return {
    id: String(apiData.id),
    siteCode: apiData.site_code || '',
    partnerId: apiData.client_id ? String(apiData.client_id) : '',
    partnerName: apiData.client?.name || '',
    siteName: apiData.name || '',
    address: apiData.address || '',
    status: apiData.status || 'unregistered',
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
  };
}

// ========================================
// API 함수
// ========================================

interface GetSiteListParams {
  size?: number;
  page?: number;
  startDate?: string;
  endDate?: string;
  search?: string;
  status?: string;
  clientId?: string;
  sortBy?: string;
}

/**
 * 현장 목록 조회
 * GET /api/v1/sites
 */
export async function getSiteList(params: GetSiteListParams = {}): Promise<{
  success: boolean;
  data?: {
    items: Site[];
    total: number;
    page: number;
    size: number;
    totalPages: number;
  };
  error?: string;
}> {
  try {
    const queryParams: Record<string, string> = {};

    // 검색
    if (params.search) queryParams.search = params.search;

    // 필터
    if (params.status && params.status !== 'all') queryParams.status = params.status;
    if (params.clientId && params.clientId !== 'all') queryParams.client_id = params.clientId;

    // 날짜 범위
    if (params.startDate) queryParams.start_date = params.startDate;
    if (params.endDate) queryParams.end_date = params.endDate;

    // 페이지네이션
    if (params.page) queryParams.page = String(params.page);
    if (params.size) queryParams.per_page = String(params.size);

    // 정렬
    if (params.sortBy) {
      const sortMap: Record<string, { field: string; dir: string }> = {
        latest: { field: 'created_at', dir: 'desc' },
        oldest: { field: 'created_at', dir: 'asc' },
        partnerNameAsc: { field: 'client_id', dir: 'asc' },
        partnerNameDesc: { field: 'client_id', dir: 'desc' },
        siteNameAsc: { field: 'name', dir: 'asc' },
        siteNameDesc: { field: 'name', dir: 'desc' },
      };
      const sort = sortMap[params.sortBy];
      if (sort) {
        queryParams.sort_by = sort.field;
        queryParams.sort_dir = sort.dir;
      }
    }

    const response = await apiClient.get<{
      success: boolean;
      data: {
        data: ApiSite[];
        current_page: number;
        per_page: number;
        total: number;
        last_page: number;
      };
    }>('/sites', { params: queryParams });

    const paginatedData = response.data;
    const items = (paginatedData.data || []).map(transformSite);

    return {
      success: true,
      data: {
        items,
        total: paginatedData.total || 0,
        page: paginatedData.current_page || 1,
        size: paginatedData.per_page || 20,
        totalPages: paginatedData.last_page || 1,
      },
    };
  } catch (error) {
    console.error('현장 목록 조회 오류:', error);
    return { success: false, error: '현장 목록을 불러오는데 실패했습니다.' };
  }
}

/**
 * 현장 통계 조회
 * GET /api/v1/sites/stats
 */
export async function getSiteStats(): Promise<{
  success: boolean;
  data?: SiteStats;
  error?: string;
}> {
  try {
    const response = await apiClient.get<{
      success: boolean;
      data: ApiSiteStats;
    }>('/sites/stats');

    const statsData = response.data;
    return {
      success: true,
      data: {
        total: statsData.total || 0,
        construction: statsData.construction || 0,
        unregistered: statsData.unregistered || 0,
        suspended: statsData.suspended || 0,
        pending: statsData.pending || 0,
      },
    };
  } catch (error) {
    console.error('현장 통계 조회 오류:', error);
    return { success: false, error: '현장 통계를 불러오는데 실패했습니다.' };
  }
}

/**
 * 현장 삭제
 * DELETE /api/v1/sites/{id}
 */
export async function deleteSite(id: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await apiClient.delete(`/sites/${id}`);
    return { success: true };
  } catch (error) {
    console.error('현장 삭제 오류:', error);
    return { success: false, error: '현장 삭제에 실패했습니다.' };
  }
}

/**
 * 현장 일괄 삭제
 * DELETE /api/v1/sites/bulk
 */
export async function deleteSites(ids: string[]): Promise<{
  success: boolean;
  deletedCount?: number;
  error?: string;
}> {
  try {
    await apiClient.delete('/sites/bulk', {
      data: { ids: ids.map((id) => Number(id)) },
    });
    return { success: true, deletedCount: ids.length };
  } catch (error) {
    console.error('현장 일괄 삭제 오류:', error);
    return { success: false, error: '현장 일괄 삭제에 실패했습니다.' };
  }
}

// ========================================
// 현장 생성/수정 타입
// ========================================

export interface CreateSiteData {
  siteName: string;
  partnerId: string;
  address?: string;
  status?: SiteStatus;
}

/**
 * 현장 등록
 * POST /api/v1/sites
 */
export async function createSite(data: CreateSiteData): Promise<{
  success: boolean;
  data?: Site;
  error?: string;
}> {
  try {
    const apiData = {
      name: data.siteName,
      client_id: data.partnerId ? Number(data.partnerId) : null,
      address: data.address || null,
      status: data.status || 'unregistered',
    };

    const response = await apiClient.post<{ success: boolean; data: ApiSite }>('/sites', apiData);
    return { success: true, data: transformSite(response.data) };
  } catch (error) {
    console.error('현장 등록 오류:', error);
    return { success: false, error: '현장 등록에 실패했습니다.' };
  }
}