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 ListDomainsRequest
{
    public Guid WorkspaceId { get; set; }
}

public class ListDomainsEndpoint(AppDbContext db)
    : Endpoint<ListDomainsRequest, DomainListResponse>
{
    public override void Configure()
    {
        Get("/workspaces/{WorkspaceId}/domains");
    }

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

        // Verify workspace ownership
        var workspaceExists = await db.Workspaces
            .AnyAsync(w => w.Id == req.WorkspaceId && w.OwnerUserId == userId, ct);

        if (!workspaceExists)
        {
            await HttpContext.Response.SendAsync(new MessageResponse("Workspace not found"), 404, cancellation: ct);
            return;
        }

        var domains = await db.Domains
            .Where(d => d.WorkspaceId == req.WorkspaceId)
            .OrderByDescending(d => d.CreatedAt)
            .Select(d => new DomainResponse(
                d.Id,
                d.WorkspaceId,
                d.Hostname,
                d.Status.ToString(),
                d.VerificationToken,
                $"TXT _trakqr-verification {d.VerificationToken}",
                d.CreatedAt
            ))
            .ToListAsync(ct);

        await HttpContext.Response.SendAsync(new DomainListResponse(domains), cancellation: ct);
    }
}