'use server';

import { buildApiUrl } from '@/lib/api/query-params';
import { executeServerAction } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import {
  type CorporateVehicleApi,
  type VehicleFormData,
  transformVehicleApi,
  transformVehicleDropdown,
} from '../types';

// ===== 차량 목록 (페이지네이션) =====
export async function getCorporateVehicles(params: {
  page?: number;
  perPage?: number;
  search?: string;
  ownershipType?: string;
  status?: string;
}) {
  return executePaginatedAction<CorporateVehicleApi, ReturnType<typeof transformVehicleApi>>({
    url: buildApiUrl('/api/v1/corporate-vehicles', {
      page: params.page,
      per_page: params.perPage,
      search: params.search,
      ownership_type: params.ownershipType !== 'all' ? params.ownershipType : undefined,
      status: params.status !== 'all' ? params.status : undefined,
    }),
    transform: transformVehicleApi,
    errorMessage: '차량 목록 조회에 실패했습니다.',
  });
}

// ===== 차량 단건 조회 =====
export async function getCorporateVehicleById(id: number) {
  return executeServerAction<CorporateVehicleApi, ReturnType<typeof transformVehicleApi>>({
    url: buildApiUrl(`/api/v1/corporate-vehicles/${id}`),
    transform: transformVehicleApi,
    errorMessage: '차량 정보 조회에 실패했습니다.',
  });
}

// ===== 차량 등록 =====
export async function createCorporateVehicle(formData: VehicleFormData) {
  const isCorporate = formData.ownershipType === 'corporate';
  return executeServerAction({
    url: buildApiUrl('/api/v1/corporate-vehicles'),
    method: 'POST',
    body: {
      plate_number: formData.plateNumber,
      model: formData.model,
      vehicle_type: formData.vehicleType,
      ownership_type: formData.ownershipType,
      year: formData.year ? Number(formData.year) : null,
      driver: formData.driver || null,
      status: formData.status || 'active',
      memo: formData.memo || null,
      // 법인
      purchase_date: isCorporate ? formData.purchaseDate || null : null,
      purchase_price: isCorporate ? Number(formData.purchasePrice) || 0 : 0,
      // 렌트/리스
      contract_date: !isCorporate ? formData.contractDate || null : null,
      rent_company: formData.rentCompany || null,
      rent_company_tel: formData.rentCompanyTel || null,
      rent_period: formData.rentPeriod || null,
      agreed_mileage: formData.agreedMileage || null,
      vehicle_price: Number(formData.vehiclePrice) || 0,
      residual_value: Number(formData.residualValue) || 0,
      deposit: Number(formData.deposit) || 0,
      monthly_rent: !isCorporate ? Number(formData.monthlyRent) || 0 : 0,
      monthly_rent_tax: Number(formData.monthlyRentTax) || 0,
      mileage: Number(formData.mileage) || 0,
      insurance_company: formData.insuranceCompany || null,
      insurance_company_tel: formData.insuranceCompanyTel || null,
    },
    errorMessage: '차량 등록에 실패했습니다.',
  });
}

// ===== 차량 수정 =====
export async function updateCorporateVehicle(id: number, formData: VehicleFormData) {
  const isCorporate = formData.ownershipType === 'corporate';
  return executeServerAction({
    url: buildApiUrl(`/api/v1/corporate-vehicles/${id}`),
    method: 'PUT',
    body: {
      plate_number: formData.plateNumber,
      model: formData.model,
      vehicle_type: formData.vehicleType,
      ownership_type: formData.ownershipType,
      year: formData.year ? Number(formData.year) : null,
      driver: formData.driver || null,
      status: formData.status || 'active',
      memo: formData.memo || null,
      purchase_date: isCorporate ? formData.purchaseDate || null : null,
      purchase_price: isCorporate ? Number(formData.purchasePrice) || 0 : 0,
      contract_date: !isCorporate ? formData.contractDate || null : null,
      rent_company: formData.rentCompany || null,
      rent_company_tel: formData.rentCompanyTel || null,
      rent_period: formData.rentPeriod || null,
      agreed_mileage: formData.agreedMileage || null,
      vehicle_price: Number(formData.vehiclePrice) || 0,
      residual_value: Number(formData.residualValue) || 0,
      deposit: Number(formData.deposit) || 0,
      monthly_rent: !isCorporate ? Number(formData.monthlyRent) || 0 : 0,
      monthly_rent_tax: Number(formData.monthlyRentTax) || 0,
      mileage: Number(formData.mileage) || 0,
      insurance_company: formData.insuranceCompany || null,
      insurance_company_tel: formData.insuranceCompanyTel || null,
    },
    errorMessage: '차량 수정에 실패했습니다.',
  });
}

// ===== 차량 삭제 =====
export async function deleteCorporateVehicle(id: number) {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/corporate-vehicles/${id}`),
    method: 'DELETE',
    errorMessage: '차량 삭제에 실패했습니다.',
  });
}

// ===== 드롭다운 목록 =====
export async function getVehicleDropdown() {
  return executeServerAction<
    Array<{ id: number; plate_number: string; model: string }>,
    ReturnType<typeof transformVehicleDropdown>[]
  >({
    url: buildApiUrl('/api/v1/corporate-vehicles/dropdown'),
    transform: (data) => data.map(transformVehicleDropdown),
    errorMessage: '차량 드롭다운 조회에 실패했습니다.',
  });
}
