-- Backfill checklist rows for existing reserve AC records.
-- This fixes historical gaps where checklist rows were not inserted.

INSERT INTO flight_inspection_file_checklists (
    id,
    is_done,
    helicopter_file_id,
    flight_inspection_id,
    created_at,
    created_by,
    updated_at,
    updated_by
)
SELECT
    UUID_TO_BIN(UUID()) AS id,
    0 AS is_done,
    hf.id AS helicopter_file_id,
    ra.inspection_id AS flight_inspection_id,
    UTC_TIMESTAMP(3) AS created_at,
    ra.created_by AS created_by,
    UTC_TIMESTAMP(3) AS updated_at,
    ra.updated_by AS updated_by
FROM reserve_acs ra
JOIN helicopter_files hf
  ON hf.helicopter_id = ra.helicopter_id
 AND hf.section IN ('bfi', 'fpwb')
LEFT JOIN flight_inspection_file_checklists fck
  ON fck.flight_inspection_id = ra.inspection_id
 AND fck.helicopter_file_id = hf.id
WHERE ra.deleted_at IS NULL
  AND fck.id IS NULL;
