package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

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

type HospitalRepository struct {
	db *gorm.DB
}

func NewHospitalRepository(db *gorm.DB) *HospitalRepository {
	return &HospitalRepository{db: db}
}

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

func (r *HospitalRepository) Update(ctx context.Context, row *hospital.Hospital) error {
	return r.db.WithContext(ctx).Save(row).Error
}

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

func (r *HospitalRepository) GetByID(ctx context.Context, id []byte) (*hospital.Hospital, error) {
	var row hospital.Hospital
	err := r.db.WithContext(ctx).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 *HospitalRepository) List(ctx context.Context, filter, sort string, limit, offset int) ([]hospital.Hospital, int64, error) {
	var rows []hospital.Hospital
	var total int64

	base := r.db.WithContext(ctx).Model(&hospital.Hospital{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where(
			"hospital_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,
		)
	}

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

	return rows, total, nil
}
