// EN: Repository implementation for Therapist aggregate.
// VI: Implementation repository cho aggregate Therapist.

using BookingService.Domain.AggregatesModel.TherapistAggregate;
using BookingService.Domain.SeedWork;
using Microsoft.EntityFrameworkCore;

namespace BookingService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for managing Therapist aggregate persistence.
/// VI: Implementation repository để quản lý persistence của aggregate Therapist.
/// </summary>
public class TherapistRepository : ITherapistRepository
{
    private readonly BookingContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public TherapistRepository(BookingContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <summary>
    /// EN: Add a new therapist to the context.
    /// VI: Thêm chuyên viên mới vào context.
    /// </summary>
    public Therapist Add(Therapist therapist)
    {
        return _context.Therapists.Add(therapist).Entity;
    }

    /// <summary>
    /// EN: Update an existing therapist in the context.
    /// VI: Cập nhật chuyên viên hiện có trong context.
    /// </summary>
    public void Update(Therapist therapist)
    {
        _context.Entry(therapist).State = EntityState.Modified;
    }

    /// <summary>
    /// EN: Get a therapist by ID.
    /// VI: Lấy chuyên viên theo ID.
    /// </summary>
    public async Task<Therapist?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.Therapists
            .FirstOrDefaultAsync(t => t.Id == id, cancellationToken);
    }

    /// <summary>
    /// EN: Get all therapists for a shop, optionally filtered by active status.
    /// VI: Lấy tất cả chuyên viên cho một shop, tùy chọn lọc theo trạng thái hoạt động.
    /// </summary>
    public async Task<List<Therapist>> GetByShopIdAsync(Guid shopId, bool? isActive = null, CancellationToken cancellationToken = default)
    {
        var query = _context.Therapists.Where(t => t.ShopId == shopId);

        if (isActive.HasValue)
        {
            query = query.Where(t => t.IsActive == isActive.Value);
        }

        return await query
            .OrderBy(t => t.Name)
            .ToListAsync(cancellationToken);
    }
}
