package mysql

import (
	"context"
	"errors"
	"time"

	"gorm.io/gorm"

	patientdata "wucher/internal/domain/patient_data"
)

type PatientDataRepository struct {
	db *gorm.DB
}

func NewPatientDataRepository(db *gorm.DB) *PatientDataRepository {
	return &PatientDataRepository{db: db}
}

func (r *PatientDataRepository) Create(ctx context.Context, row *patientdata.PatientData) error {
	return r.db.WithContext(ctx).Create(row).Error
}

func (r *PatientDataRepository) Update(ctx context.Context, row *patientdata.PatientData) error {
	return r.db.WithContext(ctx).Save(row).Error
}

func (r *PatientDataRepository) 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,
	}
	return r.db.WithContext(ctx).
		Model(&patientdata.PatientData{}).
		Where("id = ? AND deleted_at IS NULL", id).
		Updates(updates).Error
}

func (r *PatientDataRepository) GetByID(ctx context.Context, id []byte) (*patientdata.PatientData, error) {
	var row patientdata.PatientData
	err := r.db.WithContext(ctx).
		Preload("OPC", "deleted_at IS NULL").
		Preload("InsurancePatientData", "deleted_at IS NULL").
		Preload("InsurancePatientData.HealthInsuranceCompanies", "deleted_at IS NULL").
		Preload("InsurancePatientData.FederalState", "deleted_at IS NULL").
		Where("patient_data.id = ? AND patient_data.deleted_at IS NULL", id).
		First(&row).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &row, err
}

func (r *PatientDataRepository) List(ctx context.Context, filter, sort string, limit, offset int) ([]patientdata.PatientData, int64, error) {
	var rows []patientdata.PatientData
	var total int64

	base := r.db.WithContext(ctx).Model(&patientdata.PatientData{}).Where("patient_data.deleted_at IS NULL")
	if filter != "" {
		like := "%" + filter + "%"
		base = base.Where(
			"family_name LIKE ? OR first_name LIKE ? OR svnr LIKE ? OR email LIKE ? OR phone LIKE ? OR street LIKE ?",
			like, like, like, like, like, like,
		)
	}

	if err := base.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	query := base.
		Preload("OPC", "deleted_at IS NULL").
		Preload("InsurancePatientData", "deleted_at IS NULL").
		Preload("InsurancePatientData.HealthInsuranceCompanies", "deleted_at IS NULL").
		Preload("InsurancePatientData.FederalState", "deleted_at IS NULL")
	if sort != "" {
		query = query.Order(sort)
	}
	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
}
