CREATE TABLE IF NOT EXISTS helicopter_files (
    id BINARY(16) PRIMARY KEY,
    section VARCHAR(64) NOT NULL,
    helicopter_id BINARY(16) NOT NULL,
    file_attachment_id BINARY(16) NOT NULL,
    created_at DATETIME NULL,
    created_by BINARY(16) NULL,
    updated_at DATETIME NULL,
    updated_by BINARY(16) NULL,
    CONSTRAINT chk_helicopter_files_section CHECK (
        section IN (
            'before_first_flight_inspection',
            'flight_preparation_and_wb',
            'after_last_flight_inspection'
        )
    ),
    CONSTRAINT fk_helicopter_files_helicopter FOREIGN KEY (helicopter_id) REFERENCES helicopters(id),
    CONSTRAINT fk_helicopter_files_attachment FOREIGN KEY (file_attachment_id) REFERENCES attachments(id)
);

CREATE INDEX idx_helicopter_files_section ON helicopter_files(section);
CREATE INDEX idx_helicopter_files_helicopter_id ON helicopter_files(helicopter_id);
CREATE INDEX idx_helicopter_files_attachment_id ON helicopter_files(file_attachment_id);

CREATE TABLE IF NOT EXISTS flight_inspection_file_checklists (
    id BINARY(16) PRIMARY KEY,
    is_done TINYINT(1) NOT NULL DEFAULT 0,
    helicopter_file_id BINARY(16) NOT NULL,
    flight_inspection_id BINARY(16) NOT NULL,
    created_at DATETIME NULL,
    created_by BINARY(16) NULL,
    updated_at DATETIME NULL,
    updated_by BINARY(16) NULL,
    CONSTRAINT fk_flight_inspection_file_checklists_helicopter_file FOREIGN KEY (helicopter_file_id) REFERENCES helicopter_files(id),
    CONSTRAINT fk_flight_inspection_file_checklists_inspection FOREIGN KEY (flight_inspection_id) REFERENCES flight_inspections(id),
    CONSTRAINT uq_flight_inspection_file_checklists_inspection_file UNIQUE (flight_inspection_id, helicopter_file_id)
);

CREATE INDEX idx_flight_inspection_file_checklists_file_id ON flight_inspection_file_checklists(helicopter_file_id);
CREATE INDEX idx_flight_inspection_file_checklists_inspection_id ON flight_inspection_file_checklists(flight_inspection_id);
CREATE INDEX idx_flight_inspection_file_checklists_inspection_sorted ON flight_inspection_file_checklists(flight_inspection_id, is_done);
