package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

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

type MedicineRepository struct {
	db *gorm.DB
}

func NewMedicineRepository(db *gorm.DB) *MedicineRepository {
	return &MedicineRepository{db: db}
}

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

func (r *MedicineRepository) Update(ctx context.Context, row *medicine.Medicine) error {
	db := r.db.WithContext(ctx)
	if err := db.Save(row).Error; err != nil {
		return err
	}
	if row.MotorReactions != nil {
		if err := db.Model(row).Association("MotorReactions").Replace(row.MotorReactions); err != nil {
			return err
		}
	}
	return nil
}

func (r *MedicineRepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		// Allow medicine delete even when it still has reaction links by detaching M:N rows first.
		if err := tx.Where("medicine_id = ?", id).Delete(&medicine.MedicineMotorReaction{}).Error; err != nil {
			return err
		}

		if err := ensureNoReferenceBeforeDelete(ctx, tx, "medicines", id); err != nil {
			return err
		}

		now := time.Now().UTC()
		updates := map[string]any{
			"deleted_at": now,
			"deleted_by": deletedBy,
			"updated_by": deletedBy,
		}
		return mapDeleteConstraintError(tx.
			Model(&medicine.Medicine{}).
			Where("id = ? AND deleted_at IS NULL", id).
			Updates(updates).Error)
	})
}

func (r *MedicineRepository) GetByID(ctx context.Context, id []byte) (*medicine.Medicine, error) {
	var row medicine.Medicine
	err := r.db.WithContext(ctx).
		Preload("MedicineGroup", "deleted_at IS NULL").
		Preload("MotorReaction", "deleted_at IS NULL").
		Preload("MotorReactions", "deleted_at IS NULL").
		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 *MedicineRepository) List(ctx context.Context, filter, sort string, limit, offset int) ([]medicine.Medicine, int64, error) {
	var rows []medicine.Medicine
	var total int64

	base := r.db.WithContext(ctx).Model(&medicine.Medicine{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("name LIKE ? OR note LIKE ? OR pack LIKE ? OR unit LIKE ? OR CAST(`column` AS CHAR) LIKE ?", like, like, like, like, like)
	}

	query := base
	if sort != "" {
		query = query.Order(sort)
	} else {
		for _, clause := range sortkey.ActivePositiveSortClauses("medicines", "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)
	}
	query = query.
		Preload("MedicineGroup", "deleted_at IS NULL").
		Preload("MotorReaction", "deleted_at IS NULL").
		Preload("MotorReactions", "deleted_at IS NULL")
	if err := query.Find(&rows).Error; err != nil {
		return nil, 0, err
	}
	return rows, total, nil
}

func (r *MedicineRepository) CreateGroup(ctx context.Context, row *medicine.MedicineGroup) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *MedicineRepository) UpdateGroup(ctx context.Context, row *medicine.MedicineGroup) error {
	return r.db.WithContext(ctx).Save(row).Error
}

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

func (r *MedicineRepository) GetGroupByID(ctx context.Context, id []byte) (*medicine.MedicineGroup, error) {
	var row medicine.MedicineGroup
	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 *MedicineRepository) ListGroups(ctx context.Context, filter, sort string, limit, offset int) ([]medicine.MedicineGroup, int64, error) {
	var rows []medicine.MedicineGroup
	var total int64

	base := r.db.WithContext(ctx).Model(&medicine.MedicineGroup{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("name LIKE ?", like)
	}
	query := base
	if sort != "" {
		query = query.Order(sort)
	} else {
		query = query.Order("name ASC")
	}
	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
}

func (r *MedicineRepository) CreateReaction(ctx context.Context, row *medicine.MotorReaction) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *MedicineRepository) UpdateReaction(ctx context.Context, row *medicine.MotorReaction) error {
	return r.db.WithContext(ctx).Save(row).Error
}

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

func (r *MedicineRepository) GetReactionByID(ctx context.Context, id []byte) (*medicine.MotorReaction, error) {
	var row medicine.MotorReaction
	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 *MedicineRepository) ListReactions(ctx context.Context, filter, sort string, limit, offset int) ([]medicine.MotorReaction, int64, error) {
	var rows []medicine.MotorReaction
	var total int64

	base := r.db.WithContext(ctx).Model(&medicine.MotorReaction{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("name LIKE ? OR CAST(score AS CHAR) LIKE ?", like, like)
	}
	query := base
	if sort != "" {
		query = query.Order(sort)
	} else {
		query = query.Order("name ASC")
	}
	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
}
