package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

	"wucher/internal/domain/icao"
	"wucher/internal/shared/pkg/sortkey"
)

type ICAORepository struct {
	db *gorm.DB
}

func NewICAORepository(db *gorm.DB) *ICAORepository {
	return &ICAORepository{db: db}
}

func (r *ICAORepository) Create(ctx context.Context, row *icao.ICAO) error {
	requestedIsActive := row.IsActive
	db := r.db.WithContext(ctx)
	if err := db.Create(row).Error; err != nil {
		return err
	}
	return db.Model(&icao.ICAO{}).
		Where("id = ?", row.ID).
		UpdateColumn("is_active", requestedIsActive).Error
}

func (r *ICAORepository) Update(ctx context.Context, row *icao.ICAO) error {
	return r.db.WithContext(ctx).
		Omit("FederalState", "Land").
		Save(row).Error
}

func (r *ICAORepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	if err := ensureNoReferenceBeforeDelete(ctx, r.db, "icaos", id); err != nil {
		return err
	}
	now := time.Now().UTC()
	updates := map[string]any{
		"deleted_at": now,
		"deleted_by": deletedBy,
		"updated_by": deletedBy,
	}
	return mapDeleteConstraintError(r.db.WithContext(ctx).
		Model(&icao.ICAO{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error)
}

func (r *ICAORepository) GetByID(ctx context.Context, id []byte) (*icao.ICAO, error) {
	var row icao.ICAO
	err := r.db.WithContext(ctx).
		Preload("Land").
		Preload("FederalState").
		Preload("FederalState.Land").
		Where("id = ? AND deleted_at IS NULL", id).
		First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *ICAORepository) List(ctx context.Context, filter, sort string, limit, offset int) ([]icao.ICAO, int64, error) {
	var rows []icao.ICAO
	var total int64

	base := r.db.WithContext(ctx).
		Model(&icao.ICAO{}).
		Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("icao_code LIKE ? OR name LIKE ? OR address LIKE ? OR landline_number LIKE ? OR mobile_number LIKE ? OR email LIKE ? OR note LIKE ?", like, like, like, like, like, like, like)
	}

	query := base
	if sort != "" {
		query = query.Order(sort)
	} else {
		for _, clause := range sortkey.ActivePositiveSortClauses("icaos", "is_active", "sortkey", "icao_code", false) {
			query = query.Order(clause)
		}
	}
	if err := base.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	if limit > 0 {
		query = query.Limit(limit).Offset(offset)
	}
	if err := query.
		Preload("Land").
		Preload("FederalState").
		Preload("FederalState.Land").
		Find(&rows).Error; err != nil {
		return nil, 0, err
	}

	return rows, total, nil
}
