using System.Security.Claims;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;
using TrackQrApi.Features.Domains.Common;

namespace TrackQrApi.Features.Domains.Endpoints;

public class GetDomainRequest
{
    public Guid WorkspaceId { get; set; }
    public Guid Id { get; set; }
}

public class GetDomainEndpoint(AppDbContext db)
    : Endpoint<GetDomainRequest, DomainResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/domains/{Id}");
    }

    public override async Task HandleAsync(GetDomainRequest req, CancellationToken ct)
    {
        var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);

        var domain = await db.Domains
            .Where(d => d.Id == req.Id && d.WorkspaceId == req.WorkspaceId && d.Workspace.OwnerUserId == userId)
            .FirstOrDefaultAsync(ct);

        if (domain is null)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Domain not found"), 404, cancellation: ct);
            return;
        }

        var response = new DomainResponse(
            domain.Id,
            domain.WorkspaceId,
            domain.Hostname,
            domain.Status.ToString(),
            domain.VerificationToken,
            $"TXT _trakqr-verification {domain.VerificationToken}",
            domain.CreatedAt
        );

        await HttpContext.Response.SendAsync(response, cancellation: ct);
    }
}