import { Injectable, NotFoundException } from "@nestjs/common";

import { CreateTrainDto } from "./dto/create-train.dto";
import { Train } from "./entities/train.entity";
import { TrainsRepository } from "./trains.repository";

@Injectable()
export class TrainsService {
  constructor(private readonly trainsRepository: TrainsRepository) {}

  /** Register a new train in the fleet. */
  create(dto: CreateTrainDto): Promise<Train> {
    return this.trainsRepository.create(dto);
  }

  /** List every active train. */
  findAll(): Promise<Train[]> {
    return this.trainsRepository.findAll({ order: { code: "ASC" } });
  }

  /** Get a single train by ID. */
  async findById(id: string): Promise<Train> {
    const train = await this.trainsRepository.findById(id);
    if (!train) {
      throw new NotFoundException(`Train ${id} not found`);
    }
    return train;
  }
}
