import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { Yacht } from './yacht.entity';
import { CreateYachtDto } from './dto/create-yacht.dto';
import { UpdateYachtDto } from './dto/update-yacht.dto';

@Injectable()
export class YachtsService {
  private readonly logger = new Logger(YachtsService.name);

  private yachts: Yacht[] = [
    {
      yachtId: 1,
      name: 'Sea Dream',
      model: 'Sunseeker 76',
      year: 2020,
      length: 76,
      userId: 1,
      createdAt: new Date('2023-01-15'),
      updatedAt: new Date('2023-01-15'),
    },
    {
      yachtId: 2,
      name: 'Ocean Breeze',
      model: 'Princess 68',
      year: 2021,
      length: 68,
      userId: 1,
      createdAt: new Date('2023-02-20'),
      updatedAt: new Date('2023-02-20'),
    },
    {
      yachtId: 3,
      name: 'Wave Rider',
      model: 'Ferretti 70',
      year: 2019,
      length: 70,
      userId: 2,
      createdAt: new Date('2023-03-10'),
      updatedAt: new Date('2023-03-10'),
    },
  ];

  async findAll(): Promise<Yacht[]> {
    return this.yachts;
  }

  async findById(yachtId: number): Promise<Yacht> {
    const yacht = this.yachts.find((y) => y.yachtId === yachtId);
    if (!yacht) {
      throw new NotFoundException(`Yacht with ID ${yachtId} not found`);
    }
    return yacht;
  }

  async findByUserId(userId: number): Promise<Yacht[]> {
    return this.yachts.filter((y) => y.userId === userId);
  }

  async create(createYachtDto: CreateYachtDto): Promise<Yacht> {
    const newYacht: Yacht = {
      yachtId: this.yachts.length + 1,
      ...createYachtDto,
      createdAt: new Date(),
      updatedAt: new Date(),
    };
    this.yachts.push(newYacht);
    return newYacht;
  }

  async update(
    yachtId: number,
    updateYachtDto: UpdateYachtDto,
  ): Promise<Yacht> {
    const index = this.yachts.findIndex((y) => y.yachtId === yachtId);
    if (index === -1) {
      throw new NotFoundException(`Yacht with ID ${yachtId} not found`);
    }

    this.yachts[index] = {
      ...this.yachts[index],
      ...updateYachtDto,
      updatedAt: new Date(),
    };

    return this.yachts[index];
  }

  async delete(yachtId: number): Promise<void> {
    const index = this.yachts.findIndex((y) => y.yachtId === yachtId);
    if (index === -1) {
      throw new NotFoundException(`Yacht with ID ${yachtId} not found`);
    }
    this.yachts.splice(index, 1);
  }
}
