using System.Security.Claims;
using FastEndpoints;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using TrackQrApi.Data;
using TrackQrApi.Features.Auth.Common;
using TrackQrApi.Features.Projects.Common;
using TrackQrApi.Models;

namespace TrackQrApi.Features.Projects.Endpoints;

public class CreateProjectRequest
{
    public Guid WorkspaceId { get; set; }
    public string Name { get; set; } = string.Empty;
    public string? Description { get; set; }
}

public class CreateProjectValidator : Validator<CreateProjectRequest>
{
    public CreateProjectValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Name is required")
            .MaximumLength(100).WithMessage("Name must not exceed 100 characters");
    }
}

public class CreateProjectEndpoint(AppDbContext db)
    : Endpoint<CreateProjectRequest, ProjectResponse>
{
    public override void Configure()
    {
        Post("/workspaces/{WorkspaceId}/projects");
    }

    public override async Task HandleAsync(CreateProjectRequest 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 project = new Project
        {
            Id = Guid.NewGuid(),
            WorkspaceId = req.WorkspaceId,
            Name = req.Name,
            Description = req.Description,
            CreatedAt = DateTime.UtcNow
        };

        db.Projects.Add(project);
        await db.SaveChangesAsync(ct);

        var response = new ProjectResponse(
            project.Id,
            project.WorkspaceId,
            project.Name,
            project.Description,
            0, // LinkCount - new project has no links
            0, // QRCodeCount - new project has no QR codes
            project.CreatedAt
        );

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