using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Crew.GetConsentInfo;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var session = await db.CrewSession.AsNoTracking()
            .FirstOrDefaultAsync(s => s.ID == request.CrewSessionID, ct);

        if (session is null)
        {
            throw new KeyNotFoundException("세션을 찾을 수 없습니다.");
        }

        var crew = await db.Crew.AsNoTracking()
            .FirstOrDefaultAsync(c => c.ID == session.CrewID, ct);

        // 현재 사용자의 크루원 정보
        var crewMember = await db.CrewMember.AsNoTracking()
            .FirstOrDefaultAsync(m => m.CrewID == session.CrewID && m.MemberID == request.MemberID, ct);

        if (crewMember is null)
        {
            throw new KeyNotFoundException("크루원 정보를 찾을 수 없습니다.");
        }

        var consent = await db.CrewSessionConsent.AsNoTracking()
            .FirstOrDefaultAsync(c => c.CrewSessionID == request.CrewSessionID && c.CrewMemberID == crewMember.ID, ct);

        return new Response(
            session.ID,
            session.Title,
            crew?.Name ?? "",
            consent?.IsConsented ?? false,
            crewMember.ID
        );
    }
}