package beforeflightinspection

import (
	"strings"
	"time"

	"gorm.io/gorm"

	"wucher/internal/shared/pkg/uuidv7"
)

const (
	FuelUnitLT    = "LT"
	FuelUnitKG    = "KG"
	FuelUnitPOUND = "POUND"
)

type BeforeFlightInspection struct {
	ID                        []byte   `gorm:"type:binary(16);primaryKey;column:id"`
	FlightInspectionID        []byte   `gorm:"type:binary(16);not null;uniqueIndex;column:flight_inspection_id"`
	OilEngineNR1Checked       *bool    `gorm:"type:tinyint(1);column:oil_engine_nr1_checked"`
	OilEngineNR2Checked       *bool    `gorm:"type:tinyint(1);column:oil_engine_nr2_checked"`
	HydraulicLHChecked        *bool    `gorm:"type:tinyint(1);column:hydraulic_lh_checked"`
	HydraulicRHChecked        *bool    `gorm:"type:tinyint(1);column:hydraulic_rh_checked"`
	OilTransmissionMGBChecked *bool    `gorm:"type:tinyint(1);column:oil_transmission_mgb_checked"`
	OilTransmissionIGBChecked *bool    `gorm:"type:tinyint(1);column:oil_transmission_igb_checked"`
	OilTransmissionTGBChecked *bool    `gorm:"type:tinyint(1);column:oil_transmission_tgb_checked"`
	FuelAmount                *float64 `gorm:"type:decimal(10,2);column:fuel_amount"`
	FuelUnit                  string   `gorm:"type:varchar(10);check:chk_before_flight_fuel_unit,fuel_unit IS NULL OR fuel_unit IN ('LT','KG','POUND');column:fuel_unit"`
	FuelAddedAmount           *float64 `gorm:"type:decimal(10,2);column:fuel_added_amount"`
	Note                      *string  `gorm:"type:text;column:note"`

	CreatedAt time.Time `gorm:"column:created_at"`
	CreatedBy []byte    `gorm:"type:binary(16);column:created_by"`
	UpdatedAt time.Time `gorm:"column:updated_at"`
	UpdatedBy []byte    `gorm:"type:binary(16);column:updated_by"`
}

func (BeforeFlightInspection) TableName() string { return "before_flight_inspections" }

func (b *BeforeFlightInspection) BeforeCreate(tx *gorm.DB) error {
	if len(b.ID) == 0 {
		b.ID = uuidv7.MustBytes()
	}
	return nil
}

func NormalizeFuelUnit(raw string) (string, bool) {
	switch strings.ToUpper(strings.TrimSpace(raw)) {
	case "":
		return "", true
	case FuelUnitLT:
		return FuelUnitLT, true
	case FuelUnitKG:
		return FuelUnitKG, true
	case FuelUnitPOUND:
		return FuelUnitPOUND, true
	default:
		return "", false
	}
}

type ValidationError struct {
	Status  int
	Title   string
	Pointer string
	Detail  string
}

func (e *ValidationError) Error() string {
	if e == nil {
		return ""
	}
	return strings.TrimSpace(e.Detail)
}
