package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

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

type FacilityRepository struct {
	db *gorm.DB
}

func NewFacilityRepository(db *gorm.DB) *FacilityRepository {
	return &FacilityRepository{db: db}
}

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

func (r *FacilityRepository) Update(ctx context.Context, f *facility.Facility) error {
	return r.db.WithContext(ctx).Save(f).Error
}

func (r *FacilityRepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	if err := ensureNoReferenceBeforeDelete(ctx, r.db, "facilities", 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(&facility.Facility{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error)
}

func (r *FacilityRepository) GetByID(ctx context.Context, id []byte) (*facility.Facility, error) {
	var f facility.Facility
	err := r.db.WithContext(ctx).Where("id = ? AND deleted_at IS NULL", id).First(&f).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &f, err
}

func (r *FacilityRepository) List(ctx context.Context, filter, category, sort string, limit, offset int) ([]facility.Facility, int64, error) {
	var facilities []facility.Facility
	var total int64

	base := r.db.WithContext(ctx).Model(&facility.Facility{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("name LIKE ? OR type LIKE ? OR length LIKE ? OR weight LIKE ?", like, like, like, like)
	}
	if category != "" {
		base = base.Where("category = ?", category)
	}

	query := base
	if sort != "" {
		query = query.Order(sort)
	} else {
		for _, clause := range sortkey.ActivePositiveSortClauses("facilities", "is_active", "sortkey", "name", 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.Find(&facilities).Error; err != nil {
		return nil, 0, err
	}
	return facilities, total, nil
}
