using Dapper;
using FastEndpoints;
using Npgsql;
using Shared.Operations;

namespace Modules.Common.Operations.Claim;

public sealed record ClaimWorkItemsRequest(IReadOnlyList<Guid> Ids);
public sealed record ClaimWorkItemsResponse(int ClaimedCount, int SkippedCount);

public sealed class Endpoint(NpgsqlDataSource dataSource) : Endpoint<ClaimWorkItemsRequest, ClaimWorkItemsResponse>
{
    public override void Configure() { Post("/api/operations/work-items/claim"); Permissions("common.operations.claim"); }

    public override async Task HandleAsync(ClaimWorkItemsRequest req, CancellationToken ct)
    {
        var ids = req.Ids.Distinct().Take(500).ToArray();
        if (ids.Length == 0) { await Send.OkAsync(new(0, 0), ct); return; }
        var tenant = OperationsIdentity.TenantId(User);
        var actorId = OperationsIdentity.UserId(User);
        var actorName = OperationsIdentity.UserName(User);
        await using var connection = await dataSource.OpenConnectionAsync(ct);
        await using var tx = await connection.BeginTransactionAsync(ct);

        var changed = (await connection.QueryAsync<(Guid Id, string Status)>(new CommandDefinition("""
            update kbx.work_items
               set status='claimed', owner_id=@ActorId, owner_name=@ActorName, version=version+1, updated_at=now()
             where tenant_id=@Tenant and id=any(@Ids) and status='open'
         returning id, 'open'::text as Status;
        """, new { Tenant = tenant, Ids = ids, ActorId = actorId, ActorName = actorName }, tx, cancellationToken: ct))).AsList();

        foreach (var row in changed)
            await connection.ExecuteAsync(new CommandDefinition("""
                insert into kbx.work_item_audit(id, work_item_id, tenant_id, action, actor_id, actor_name, before_status, after_status)
                values(@Id, @WorkItemId, @Tenant, 'claim', @ActorId, @ActorName, 'open', 'claimed');
            """, new { Id = Guid.NewGuid(), WorkItemId = row.Id, Tenant = tenant, ActorId = actorId, ActorName = actorName }, tx, cancellationToken: ct));

        await tx.CommitAsync(ct);
        await Send.OkAsync(new(changed.Count, ids.Length - changed.Count), ct);
    }
}
