using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Identity;
using Baya.Domain.Entities.Identity;
using Baya.Infrastructure.Persistence.Repositories.Common;
using Microsoft.EntityFrameworkCore;

namespace Baya.Infrastructure.Persistence.Repositories;

internal sealed class CustomerProfileRepository : BaseAsyncRepository<CustomerProfile>, ICustomerProfileRepository
{
    public CustomerProfileRepository(ApplicationDbContext dbContext) : base(dbContext)
    {
    }

    public Task<CustomerProfile> GetByUserIdAsync(int userId, CancellationToken cancellationToken)
        => Table.FirstOrDefaultAsync(c => c.UserId == userId, cancellationToken);

    public Task AddAsync(CustomerProfile profile, CancellationToken cancellationToken)
        => base.AddAsync(profile);

    public Task<CustomerProfileDto> GetMineAsync(int userId, CancellationToken cancellationToken)
        => TableNoTracking
            .Where(c => c.UserId == userId)
            .Select(c => new CustomerProfileDto(
                c.Id, c.DefaultEmergencyContactName, c.DefaultEmergencyContactPhone, c.AvatarUrl, c.PreferredLanguage))
            .FirstOrDefaultAsync(cancellationToken);

    public Task<long?> GetProfileIdByUserIdAsync(int userId, CancellationToken cancellationToken)
        => TableNoTracking
            .Where(c => c.UserId == userId)
            .Select(c => (long?)c.Id)
            .FirstOrDefaultAsync(cancellationToken);

    public Task<int?> GetUserIdByProfileIdAsync(long customerProfileId, CancellationToken cancellationToken)
        => TableNoTracking
            .Where(c => c.Id == customerProfileId)
            .Select(c => (int?)c.UserId)
            .FirstOrDefaultAsync(cancellationToken);
}
