| | | 1 | | using MechanicsSoftware.Application.Abstractions; |
| | | 2 | | using MechanicsSoftware.Application.Exceptions; |
| | | 3 | | using MechanicsSoftware.Application.UseCases.Vehicles.Commands; |
| | | 4 | | using MechanicsSoftware.Domain.Entities; |
| | | 5 | | using MechanicsSoftware.Domain.Exceptions; |
| | | 6 | | using MechanicsSoftware.Domain.ValueObjects; |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | |
| | | 9 | | namespace MechanicsSoftware.Application.UseCases.Vehicles.Handlers; |
| | | 10 | | |
| | 10 | 11 | | public sealed class CreateVehicleHandler(IAppDbContext db) |
| | | 12 | | { |
| | | 13 | | public async Task<VehicleResponse> ExecuteAsync( |
| | | 14 | | CreateVehicleCommand command, |
| | | 15 | | CancellationToken cancellationToken = default) |
| | 10 | 16 | | { |
| | 10 | 17 | | var customerExists = await db.Customers |
| | 10 | 18 | | .AnyAsync(c => c.Id == command.CustomerId, cancellationToken); |
| | | 19 | | |
| | 10 | 20 | | if (!customerExists) |
| | 2 | 21 | | throw new NotFoundException(nameof(Customer), command.CustomerId); |
| | | 22 | | |
| | 8 | 23 | | var plate = new LicensePlate(command.LicensePlate); |
| | | 24 | | |
| | 6 | 25 | | var plateExists = await db.Vehicles |
| | 6 | 26 | | .AnyAsync(v => v.LicensePlate == plate, cancellationToken); |
| | | 27 | | |
| | 6 | 28 | | if (plateExists) |
| | 2 | 29 | | throw new DomainException($"License plate '{plate}' is already registered."); |
| | | 30 | | |
| | 4 | 31 | | var vehicle = Vehicle.Create( |
| | 4 | 32 | | Guid.NewGuid(), plate, command.Make, command.Model, command.Year, command.CustomerId); |
| | | 33 | | |
| | 4 | 34 | | db.Vehicles.Add(vehicle); |
| | 4 | 35 | | await db.SaveChangesAsync(cancellationToken); |
| | | 36 | | |
| | 4 | 37 | | return VehicleResponse.From(vehicle); |
| | 4 | 38 | | } |
| | | 39 | | } |