package repository

import (
	"context"

	"eslogad-be/internal/entities"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type DispositionRouteRepository struct{ db *gorm.DB }

func NewDispositionRouteRepository(db *gorm.DB) *DispositionRouteRepository {
	return &DispositionRouteRepository{db: db}
}

func (r *DispositionRouteRepository) Create(ctx context.Context, e *entities.DispositionRoute) error {
	db := DBFromContext(ctx, r.db)
	return db.WithContext(ctx).Create(e).Error
}
func (r *DispositionRouteRepository) Update(ctx context.Context, e *entities.DispositionRoute) error {
	db := DBFromContext(ctx, r.db)
	return db.WithContext(ctx).Model(&entities.DispositionRoute{}).Where("id = ?", e.ID).Updates(e).Error
}
func (r *DispositionRouteRepository) Get(ctx context.Context, id uuid.UUID) (*entities.DispositionRoute, error) {
	db := DBFromContext(ctx, r.db)
	var e entities.DispositionRoute
	if err := db.WithContext(ctx).
		Preload("FromDepartment").
		Preload("ToDepartment").
		First(&e, "id = ?", id).Error; err != nil {
		return nil, err
	}
	return &e, nil
}
func (r *DispositionRouteRepository) ListByFromDept(ctx context.Context, fromDept uuid.UUID) ([]entities.DispositionRoute, error) {
	db := DBFromContext(ctx, r.db)
	var list []entities.DispositionRoute
	if err := db.WithContext(ctx).Where("from_department_id = ?", fromDept).
		Preload("FromDepartment").
		Preload("ToDepartment").
		Order("to_department_id").Find(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}

func (r *DispositionRouteRepository) SetActive(ctx context.Context, id uuid.UUID, isActive bool) error {
	db := DBFromContext(ctx, r.db)
	return db.WithContext(ctx).Model(&entities.DispositionRoute{}).Where("id = ?", id).Update("is_active", isActive).Error
}
