import {
  Injectable,
  ConflictException,
  NotFoundException,
  ForbiddenException,
} from '@nestjs/common';
import { VehicleTypeRepository } from './repositories/vehicle-type.repository';
import { CreateVehicleTypeDto, UpdateVehicleTypeDto } from './dto';
import { serviceMessages } from '../../common/constants/messages';

const MSG = serviceMessages('Vehicle type');

@Injectable()
export class VehicleTypeService {
  constructor(private readonly repo: VehicleTypeRepository) {}

  async findAll(query?: { page?: number; limit?: number; search?: string }) {
    return this.repo.findPaginated({
      page: query?.page,
      limit: query?.limit,
      search: query?.search,
      searchColumns: ['name'],
      order: { name: 'ASC' },
    });
  }

  async findAllActive() {
    return this.repo.findAllActive();
  }

  async findAllForLookup() {
    return this.repo.find({
      where: { is_active: true } as any,
      select: ['id', 'name'],
      order: { name: 'ASC' } as any,
    });
  }

  async findById(id: string) {
    const item = await this.repo.findById(id);
    if (!item) throw new NotFoundException(MSG.NOT_FOUND);
    return item;
  }

  async create(dto: CreateVehicleTypeDto) {
    const existing = await this.repo.findByName(dto.name);
    if (existing) throw new ConflictException(MSG.ALREADY_EXISTS('name'));

    const item = await this.repo.save({
      name: dto.name,
      is_active: dto.is_active ?? true,
      is_system: false,
    });

    return { id: item.id, message: MSG.CREATED };
  }

  async update(id: string, dto: UpdateVehicleTypeDto) {
    const item = await this.repo.findById(id);
    if (!item) throw new NotFoundException(MSG.NOT_FOUND);

    if (dto.name && dto.name !== item.name) {
      const existing = await this.repo.findByName(dto.name);
      if (existing && existing.id !== id) throw new ConflictException(MSG.ALREADY_EXISTS('name'));
    }

    const updateData: any = {};
    for (const field of ['name', 'is_active']) {
      if ((dto as any)[field] !== undefined) updateData[field] = (dto as any)[field];
    }

    await this.repo.update(id, updateData);
    return { id, message: MSG.UPDATED };
  }

  async remove(id: string) {
    const item = await this.repo.findById(id);
    if (!item) throw new NotFoundException(MSG.NOT_FOUND);
    if (item.is_system) throw new ForbiddenException(MSG.CANNOT_DELETE_SYSTEM);

    await this.repo.softDelete(id);
    return { message: MSG.DELETED };
  }
}
