-- Migration: Migrate existing vehicle TCO data to ownership_costs table
-- Issue: #15
-- Description: Copy insurance and registration costs from vehicles table to ownership_costs

-- Insert insurance costs from vehicles that have insurance data
INSERT INTO ownership_costs (
  user_id,
  vehicle_id,
  document_id,
  cost_type,
  description,
  amount,
  interval,
  start_date,
  end_date
)
SELECT
  v.user_id,
  v.id AS vehicle_id,
  NULL AS document_id,
  'insurance' AS cost_type,
  'Migrated from vehicle record' AS description,
  v.insurance_cost AS amount,
  v.insurance_interval AS interval,
  COALESCE(v.purchase_date, v.created_at::date) AS start_date,
  NULL AS end_date
FROM vehicles v
WHERE v.insurance_cost IS NOT NULL
  AND v.insurance_cost > 0
  AND v.insurance_interval IS NOT NULL
  AND v.is_active = true
  AND NOT EXISTS (
    -- Only migrate if no insurance cost already exists for this vehicle
    SELECT 1 FROM ownership_costs oc
    WHERE oc.vehicle_id = v.id
      AND oc.cost_type = 'insurance'
      AND oc.description = 'Migrated from vehicle record'
  );

-- Insert registration costs from vehicles that have registration data
INSERT INTO ownership_costs (
  user_id,
  vehicle_id,
  document_id,
  cost_type,
  description,
  amount,
  interval,
  start_date,
  end_date
)
SELECT
  v.user_id,
  v.id AS vehicle_id,
  NULL AS document_id,
  'registration' AS cost_type,
  'Migrated from vehicle record' AS description,
  v.registration_cost AS amount,
  v.registration_interval AS interval,
  COALESCE(v.purchase_date, v.created_at::date) AS start_date,
  NULL AS end_date
FROM vehicles v
WHERE v.registration_cost IS NOT NULL
  AND v.registration_cost > 0
  AND v.registration_interval IS NOT NULL
  AND v.is_active = true
  AND NOT EXISTS (
    -- Only migrate if no registration cost already exists for this vehicle
    SELECT 1 FROM ownership_costs oc
    WHERE oc.vehicle_id = v.id
      AND oc.cost_type = 'registration'
      AND oc.description = 'Migrated from vehicle record'
  );
