package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

	insurancepatientdata "wucher/internal/domain/insurance_patient_data"
)

type InsurancePatientDataRepository struct {
	db *gorm.DB
}

func NewInsurancePatientDataRepository(db *gorm.DB) *InsurancePatientDataRepository {
	return &InsurancePatientDataRepository{db: db}
}

func (r *InsurancePatientDataRepository) Create(ctx context.Context, row *insurancepatientdata.InsurancePatientData) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *InsurancePatientDataRepository) Update(ctx context.Context, row *insurancepatientdata.InsurancePatientData) error {
	return r.db.WithContext(ctx).Save(row).Error
}

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

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

	base := r.db.WithContext(ctx).Model(&insurancepatientdata.InsurancePatientData{}).Where("deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where("HEX(health_insurance_companies_id) LIKE ? OR HEX(federal_state_id) LIKE ?", like, like)
	}

	query := base.
		Preload("HealthInsuranceCompanies", "deleted_at IS NULL").
		Preload("FederalState", "deleted_at IS NULL")
	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
}
