'use server';

/**
 * 차량 관리 서버 액션
 * 레거시 5130 사이트 컬럼 구조 기반 (2025-01-28 스크린샷 검증)
 */

import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { Vehicle, VehicleFormData, ActionResponse, ListResponse } from '../types';

// ===== Mock 데이터 (API 연동 전까지 사용) =====
const mockVehicles: Vehicle[] = [
  {
    id: '1',
    vehicleNumber: '83버5277',
    vehicleType: '포터',
    purchaseType: '회사 소유',
    firstRegistrationDate: '2022-01-15',
    managerMain: '이재만',
    managerSub: '',
    purchaseDate: '2023-01-15',
    leaseEndDate: '',
    totalMileage: '92000',
    mileageRecordDate: '2025-01-15',
    inspectionStartDate: '2025-01-01',
    inspectionEndDate: '2025-12-31',
    insuranceJoinDate: '2023-01-01',
    insuranceCompany: '한화손해보험, 12345678',
    insuranceContact: '1566-8000',
    insuranceFee: '500000',
    insuranceAmount: '50000000',
    oilChangeCycle: '10000',
    oilChangeRecords: [
      { id: 'oil-1-1', date: '2025-01-15', mileage: '92000', cost: '50000' },
    ],
    maintenanceRecords: [
      { id: 'maint-1-1', date: '2025-10-01', description: '오일교환, 브레이크라이닝2개교체', cost: '150000' },
    ],
    remarks: '',
  },
  {
    id: '2',
    vehicleNumber: '81러8178',
    vehicleType: '봉고III 1.2톤',
    purchaseType: '회사 소유',
    firstRegistrationDate: '2016-06-16',
    managerMain: '김진호선임',
    managerSub: '',
    purchaseDate: '2016-06-16',
    leaseEndDate: '',
    totalMileage: '92000',
    mileageRecordDate: '2024-12-12',
    inspectionStartDate: '2025-06-01',
    inspectionEndDate: '2025-06-16',
    insuranceJoinDate: '2016-06-16',
    insuranceCompany: '한화손해보험',
    insuranceContact: '1566-8000',
    insuranceFee: '',
    insuranceAmount: '',
    oilChangeCycle: '10000',
    oilChangeRecords: [
      { id: 'oil-2-1', date: '2024-12-12', mileage: '92000', cost: '' },
    ],
    maintenanceRecords: [
      { id: 'maint-2-1', date: '2024-12-19', description: '차량검사 완료', cost: '' },
      { id: 'maint-2-2', date: '2025-05-22', description: '디스크 삼발이 교체', cost: '' },
      { id: 'maint-2-3', date: '2025-06-17', description: '후방 소음기 파손 교체', cost: '' },
    ],
    remarks: '',
  },
  {
    id: '3',
    vehicleNumber: '81러8197',
    vehicleType: '그랜드 스타렉스',
    purchaseType: '회사 소유',
    firstRegistrationDate: '2016-06-22',
    managerMain: '황규선',
    managerSub: '',
    purchaseDate: '2016-06-22',
    leaseEndDate: '',
    totalMileage: '',
    mileageRecordDate: '',
    inspectionStartDate: '',
    inspectionEndDate: '',
    insuranceJoinDate: '2016-06-22',
    insuranceCompany: '한화손해보험',
    insuranceContact: '1566-8000',
    insuranceFee: '',
    insuranceAmount: '',
    oilChangeCycle: '',
    oilChangeRecords: [],
    maintenanceRecords: [
      { id: 'maint-3-1', date: '2025-08-18', description: '앞바퀴 타이어 교체', cost: '' },
      { id: 'maint-3-2', date: '2025-10-01', description: '오일교환 및 에어컨필터교환', cost: '' },
      { id: 'maint-3-3', date: '2025-12-04', description: '오일교환', cost: '' },
    ],
    remarks: '',
  },
  {
    id: '4',
    vehicleNumber: '80소0595',
    vehicleType: '코란도스포츠',
    purchaseType: '회사 소유',
    firstRegistrationDate: '2017-08-14',
    managerMain: '이세희차장',
    managerSub: '',
    purchaseDate: '2017-08-14',
    leaseEndDate: '',
    totalMileage: '16400',
    mileageRecordDate: '2025-01-15',
    inspectionStartDate: '',
    inspectionEndDate: '',
    insuranceJoinDate: '2017-08-14',
    insuranceCompany: '한화손해보험',
    insuranceContact: '1566-8000',
    insuranceFee: '',
    insuranceAmount: '',
    oilChangeCycle: '',
    oilChangeRecords: [
      { id: 'oil-4-1', date: '2025-01-15', mileage: '16400', cost: '' },
    ],
    maintenanceRecords: [
      { id: 'maint-4-1', date: '2025-01-15', description: '베터리 교체(솔라이트90r)', cost: '' },
    ],
    remarks: '2025.8.8차량매각(주식회사 차들)',
  },
  {
    id: '5',
    vehicleNumber: '224호9739',
    vehicleType: '레이',
    purchaseType: '렌트',
    firstRegistrationDate: '2024-10-25',
    managerMain: '공장',
    managerSub: '',
    purchaseDate: '2024-10-25',
    leaseEndDate: '',
    totalMileage: '',
    mileageRecordDate: '',
    inspectionStartDate: '',
    inspectionEndDate: '',
    insuranceJoinDate: '2024-10-25',
    insuranceCompany: '메리츠캐피탈',
    insuranceContact: '1588-9666',
    insuranceFee: '',
    insuranceAmount: '',
    oilChangeCycle: '7000',
    oilChangeRecords: [],
    maintenanceRecords: [
      { id: 'maint-5-1', date: '2025-06-25', description: '배터리 및 메인휴즈교체', cost: '' },
    ],
    remarks: '긴급출동 연락처:1577-0565',
  },
];

// ===== 차량 목록 조회 =====
export async function getVehicles(params?: {
  page?: number;
  perPage?: number;
  search?: string;
}): Promise<ListResponse<Vehicle>> {
  try {
    let filteredData = [...mockVehicles];

    if (params?.search) {
      const search = params.search.toLowerCase();
      filteredData = filteredData.filter(
        (v) =>
          v.vehicleNumber.toLowerCase().includes(search) ||
          v.vehicleType.toLowerCase().includes(search) ||
          v.managerMain.toLowerCase().includes(search) ||
          v.insuranceCompany.toLowerCase().includes(search)
      );
    }

    return {
      success: true,
      data: filteredData,
      totalCount: filteredData.length,
      totalPages: 1,
    };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[VehicleActions] getVehicles error:', error);
    return {
      success: false,
      data: [],
      totalCount: 0,
      totalPages: 0,
      error: '차량 목록 조회 중 오류가 발생했습니다.',
    };
  }
}

// ===== 차량 단건 조회 =====
export async function getVehicleById(id: string): Promise<ActionResponse<Vehicle>> {
  try {
    const vehicle = mockVehicles.find((v) => v.id === id);
    if (!vehicle) {
      return { success: false, error: '차량을 찾을 수 없습니다.' };
    }
    return { success: true, data: vehicle };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[VehicleActions] getVehicleById error:', error);
    return {
      success: false,
      error: '차량 조회 중 오류가 발생했습니다.',
    };
  }
}

// ===== 차량 생성 =====
export async function createVehicle(
  formData: Partial<VehicleFormData>
): Promise<ActionResponse<Vehicle>> {
  try {
    const newVehicle: Vehicle = {
      id: String(Date.now()),
      vehicleNumber: formData.vehicleNumber || '',
      vehicleType: formData.vehicleType || '',
      purchaseType: formData.purchaseType || '',
      firstRegistrationDate: formData.firstRegistrationDate || '',
      managerMain: formData.managerMain || '',
      managerSub: formData.managerSub || '',
      purchaseDate: formData.purchaseDate || '',
      leaseEndDate: formData.leaseEndDate || '',
      totalMileage: formData.totalMileage || '',
      mileageRecordDate: formData.mileageRecordDate || '',
      inspectionStartDate: formData.inspectionStartDate || '',
      inspectionEndDate: formData.inspectionEndDate || '',
      insuranceJoinDate: formData.insuranceJoinDate || '',
      insuranceCompany: formData.insuranceCompany || '',
      insuranceContact: formData.insuranceContact || '',
      insuranceFee: formData.insuranceFee || '',
      insuranceAmount: formData.insuranceAmount || '',
      oilChangeCycle: formData.oilChangeCycle || '',
      oilChangeRecords: formData.oilChangeRecords || [],
      maintenanceRecords: formData.maintenanceRecords || [],
      remarks: formData.remarks || '',
    };
    mockVehicles.push(newVehicle);
    return { success: true, data: newVehicle };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[VehicleActions] createVehicle error:', error);
    return {
      success: false,
      error: '차량 등록 중 오류가 발생했습니다.',
    };
  }
}

// ===== 차량 수정 =====
export async function updateVehicle(
  id: string,
  formData: Partial<VehicleFormData>
): Promise<ActionResponse<Vehicle>> {
  try {
    const index = mockVehicles.findIndex((v) => v.id === id);
    if (index === -1) {
      return { success: false, error: '차량을 찾을 수 없습니다.' };
    }
    mockVehicles[index] = {
      ...mockVehicles[index],
      ...formData,
    };
    return { success: true, data: mockVehicles[index] };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[VehicleActions] updateVehicle error:', error);
    return {
      success: false,
      error: '차량 수정 중 오류가 발생했습니다.',
    };
  }
}

// ===== 차량 삭제 =====
export async function deleteVehicle(id: string): Promise<ActionResponse> {
  try {
    const index = mockVehicles.findIndex((v) => v.id === id);
    if (index === -1) {
      return { success: false, error: '차량을 찾을 수 없습니다.' };
    }
    mockVehicles.splice(index, 1);
    return { success: true };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[VehicleActions] deleteVehicle error:', error);
    return {
      success: false,
      error: '차량 삭제 중 오류가 발생했습니다.',
    };
  }
}

// ===== 차량 일괄 삭제 =====
export async function bulkDeleteVehicles(ids: string[]): Promise<ActionResponse> {
  try {
    ids.forEach((id) => {
      const index = mockVehicles.findIndex((v) => v.id === id);
      if (index !== -1) {
        mockVehicles.splice(index, 1);
      }
    });
    return { success: true };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    console.error('[VehicleActions] bulkDeleteVehicles error:', error);
    return {
      success: false,
      error: '차량 일괄 삭제 중 오류가 발생했습니다.',
    };
  }
}
