package mysql

import (
	"context"
	"errors"

	"gorm.io/gorm"

	beforeflightinspection "wucher/internal/domain/before_flight_inspection"
	flightinspection "wucher/internal/domain/flight_inspection"
	"wucher/internal/domain/helicopter"
)

type BeforeFlightInspectionRepository struct {
	db *gorm.DB
}

func NewBeforeFlightInspectionRepository(db *gorm.DB) *BeforeFlightInspectionRepository {
	return &BeforeFlightInspectionRepository{db: db}
}

func (r *BeforeFlightInspectionRepository) Upsert(ctx context.Context, row *beforeflightinspection.BeforeFlightInspection) error {
	return r.db.WithContext(ctx).Save(row).Error
}

func (r *BeforeFlightInspectionRepository) GetByFlightInspectionID(ctx context.Context, flightInspectionID []byte) (*beforeflightinspection.BeforeFlightInspection, error) {
	var rows []beforeflightinspection.BeforeFlightInspection
	err := r.db.WithContext(ctx).Where("flight_inspection_id = ?", flightInspectionID).Limit(1).Find(&rows).Error
	if err != nil {
		return nil, err
	}
	if len(rows) == 0 {
		return nil, nil
	}
	return &rows[0], nil
}

func (r *BeforeFlightInspectionRepository) FlightInspectionExists(ctx context.Context, flightInspectionID []byte) (bool, error) {
	if len(flightInspectionID) != 16 {
		return false, nil
	}
	var total int64
	err := r.db.WithContext(ctx).
		Model(&flightinspection.FlightInspection{}).
		Where("id = ?", flightInspectionID).
		Count(&total).Error
	return total > 0, err
}

func (r *BeforeFlightInspectionRepository) GetHelicopterCapabilities(ctx context.Context, flightInspectionID []byte) (*beforeflightinspection.HelicopterCapabilities, error) {
	var caps beforeflightinspection.HelicopterCapabilities
	tx := r.db.WithContext(ctx).
		Model(&helicopter.Helicopter{}).
		Joins("JOIN reserve_acs ra ON ra.helicopter_id = helicopters.id").
		Where("ra.inspection_id = ? AND ra.deleted_at IS NULL", flightInspectionID).
		Select("helicopters.nr1, helicopters.nr2, helicopters.lh, helicopters.rh, helicopters.mgb, helicopters.igb, helicopters.tgb").
		Limit(1).
		Scan(&caps)
	if tx.Error != nil {
		return nil, tx.Error
	}
	if tx.RowsAffected == 0 {
		return nil, errors.New("helicopter not found for flight inspection")
	}
	return &caps, nil
}
