package mysql

import (
	"context"
	"errors"

	"gorm.io/gorm"

	fleethistory "wucher/internal/domain/fleet_history"
)

type FleetHistoryRepository struct{ db *gorm.DB }

func NewFleetHistoryRepository(db *gorm.DB) *FleetHistoryRepository {
	return &FleetHistoryRepository{db: db}
}

func (r *FleetHistoryRepository) Create(ctx context.Context, row *fleethistory.FleetHistory) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *FleetHistoryRepository) ListByHelicopter(ctx context.Context, helicopterID []byte, limit, offset int) ([]fleethistory.FleetHistory, int64, error) {
	rows := make([]fleethistory.FleetHistory, 0)
	var total int64
	base := r.db.WithContext(ctx).
		Model(&fleethistory.FleetHistory{}).
		Where("helicopter_id = ?", helicopterID)
	if err := base.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	q := base.Order("created_at DESC")
	if limit > 0 {
		q = q.Limit(limit).Offset(offset)
	}
	err := q.Find(&rows).Error
	return rows, total, err
}

func (r *FleetHistoryRepository) HelicopterIDByInspection(ctx context.Context, inspectionID []byte) ([]byte, error) {
	var out []byte
	err := r.db.WithContext(ctx).
		Table("reserve_acs").
		Select("helicopter_id").
		Where("inspection_id = ?", inspectionID).
		Limit(1).
		Scan(&out).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return out, err
}
