2026-02-13 11:05:57 -06:00
namespace FiscalOS.API.Accounts.Add ;
internal static class Endpoint
{
private const string Route = "/" ;
public static RouteHandlerBuilder MapAddEndpoint ( this RouteGroupBuilder groupBuilder )
{
return groupBuilder . MapPost ( Route , HandleAsync );
}
private static async Task < IResult > HandleAsync (
HttpContext httpContext ,
[FromBody] Request request ,
[FromServices] AppDbContext appDbContext ,
CancellationToken ct
)
{
var userId = httpContext . GetUserId ();
var user = await appDbContext . Users
2026-02-13 12:05:01 -06:00
. Include ( u => u . Institutions . Where ( i => i . Metadata is PlaidMetadata && (( PlaidMetadata ) i . Metadata ). PlaidId == request . PlaidInstitutionId ))
2026-02-13 11:05:57 -06:00
. Include ( u => u . Accounts . Where ( a => a . Metadata is PlaidAccountMetadata && (( PlaidAccountMetadata ) a . Metadata ). PlaidId == request . PlaidAccountId ))
. ThenInclude ( a => a . Metadata )
. SingleOrDefaultAsync ( u => u . Id == userId , ct );
if ( user is null )
{
return Results . Unauthorized ();
}
2026-02-13 12:05:01 -06:00
if ( user . Institutions . Any () is false )
{
return Results . ValidationProblem ( new Dictionary < string , string []>
{
["PlaidInstitutionId"] = [ "The PlaidInstitutionId field is invalid. No institution connected with the given PlaidInstitutionId was found for the user." ],
});
}
2026-02-13 11:05:57 -06:00
if ( user . Accounts . Any ())
{
return Results . Conflict ();
}
2026-02-13 12:05:01 -06:00
var accountMetadata = PlaidAccountMetadata . From ( request . PlaidAccountId , request . PlaidAccountName );
var account = Account . From ( user . Institutions . First (). Id , request . PlaidAccountName , accountMetadata );
2026-02-14 06:44:37 -06:00
var balance = Balance . From ( request . AccountCurrentBalance , request . AccountAvailableBalance , request . AccountCurrencyCode );
2026-02-14 05:54:12 -06:00
account . AddBalance ( balance );
2026-02-13 12:05:01 -06:00
user . AddAccount ( account );
await appDbContext . SaveChangesAsync ( ct );
2026-02-13 11:05:57 -06:00
return Results . Ok ();
}
}