package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

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

type VocationRepository struct {
	db *gorm.DB
}

func NewVocationRepository(db *gorm.DB) *VocationRepository {
	return &VocationRepository{db: db}
}

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

func (r *VocationRepository) Update(ctx context.Context, v *vocation.Vocation) error {
	return r.db.WithContext(ctx).Save(v).Error
}

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

func (r *VocationRepository) GetByID(ctx context.Context, id []byte) (*vocation.Vocation, error) {
	var row vocation.Vocation
	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 *VocationRepository) List(ctx context.Context, filter, sort string, limit, offset int) ([]vocation.Vocation, int64, error) {
	var rows []vocation.Vocation
	var total int64

	base := r.db.WithContext(ctx).Model(&vocation.Vocation{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("name LIKE ? OR note LIKE ?", like, like)
	}

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