package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

	"wucher/internal/domain/operation"
)

type HEMSOperationRepository struct {
	db *gorm.DB
}

func NewHEMSOperationRepository(db *gorm.DB) *HEMSOperationRepository {
	return &HEMSOperationRepository{db: db}
}

func (r *HEMSOperationRepository) Create(ctx context.Context, row *operation.HEMSOperation) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *HEMSOperationRepository) Update(ctx context.Context, row *operation.HEMSOperation) error {
	return r.db.WithContext(ctx).
		Model(&operation.HEMSOperation{}).
		Where("id = ? AND deleted_at IS NULL", row.ID).
		Updates(map[string]any{
			"date":                       row.Date,
			"operational_data_id":        nullableBytes(row.OperationalDataID),
			"mission_id":                 nullableBytes(row.MissionID),
			"hems_operation_category_id": nullableBytes(row.HEMSOperationCategoryID),
			"updated_by":                 row.UpdatedBy,
			"updated_at":                 time.Now().UTC(),
		}).Error
}

func (r *HEMSOperationRepository) Delete(ctx context.Context, id []byte, deletedBy []byte) error {
	now := time.Now().UTC()
	updates := map[string]any{
		"deleted_at": now,
		"deleted_by": deletedBy,
		"updated_by": deletedBy,
		"updated_at": now,
	}
	return r.db.WithContext(ctx).
		Model(&operation.HEMSOperation{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error
}

func (r *HEMSOperationRepository) GetByID(ctx context.Context, id []byte) (*operation.HEMSOperation, error) {
	var row operation.HEMSOperation
	err := r.db.WithContext(ctx).
		Preload("OperationalData").
		Preload("Mission").
		Preload("HEMSOperationCategory").
		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 *HEMSOperationRepository) List(ctx context.Context, filter string, sort string, limit, offset int) ([]operation.HEMSOperation, int64, error) {
	var rows []operation.HEMSOperation
	var total int64

	base := r.db.WithContext(ctx).Model(&operation.HEMSOperation{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("DATE_FORMAT(date, '%Y-%m-%dT%H:%i:%sZ') LIKE ?", like)
	}

	query := base.Preload("OperationalData").Preload("Mission").Preload("HEMSOperationCategory")
	if sort != "" {
		query = query.Order(sort)
	}
	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
}
