package mysql

import (
	"context"
	"errors"

	"gorm.io/gorm"

	flightprepcheck "wucher/internal/domain/flight_prep_check"
)

type FlightPrepCheckRepository struct {
	db *gorm.DB
}

func NewFlightPrepCheckRepository(db *gorm.DB) *FlightPrepCheckRepository {
	return &FlightPrepCheckRepository{db: db}
}

func (r *FlightPrepCheckRepository) Create(ctx context.Context, check *flightprepcheck.FlightPrepCheck) error {
	return r.db.WithContext(ctx).Create(check).Error
}

func (r *FlightPrepCheckRepository) Update(ctx context.Context, check *flightprepcheck.FlightPrepCheck) error {
	return r.db.WithContext(ctx).Save(check).Error
}

func (r *FlightPrepCheckRepository) GetByID(ctx context.Context, id []byte) (*flightprepcheck.FlightPrepCheck, error) {
	var check flightprepcheck.FlightPrepCheck
	err := r.db.WithContext(ctx).Where("id = ?", id).First(&check).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &check, err
}

func (r *FlightPrepCheckRepository) GetByFlightInspectionID(ctx context.Context, flightInspectionID []byte) (*flightprepcheck.FlightPrepCheck, error) {
	var check flightprepcheck.FlightPrepCheck
	err := r.db.WithContext(ctx).Where("flight_inspection_id = ?", flightInspectionID).First(&check).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &check, err
}
