import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../common/prisma.service';
import { CreateStationDto } from './stations.dto';

interface StationFilters {
  search?: string;
  country?: string;
  operational?: string;
}

@Injectable()
export class StationsService {
  constructor(private prisma: PrismaService) {}
  
  findAll(filters: StationFilters = {}) {
    const where: any = {};
    
    if (filters.search) {
      where.OR = [
        { name: { contains: filters.search, mode: 'insensitive' } },
        { code: { contains: filters.search, mode: 'insensitive' } },
        { city: { contains: filters.search, mode: 'insensitive' } },
      ];
    }
    
    if (filters.country) {
      where.countryCode = filters.country;
    }
    
    if (filters.operational !== undefined && filters.operational !== '') {
      where.isOperational = filters.operational === 'true';
    }
    
    return this.prisma.station.findMany({ 
      where,
      orderBy: { name: 'asc' } 
    }); 
  }
  
  async findOne(id: string) {
    const s = await this.prisma.station.findUnique({ where: { id } });
    if (!s) throw new NotFoundException('Station not found');
    return s;
  }
  
  create(dto: CreateStationDto) { 
    return this.prisma.station.create({ data: dto }); 
  }

  async update(id: string, dto: Partial<CreateStationDto>) {
    await this.findOne(id); // Check if exists
    return this.prisma.station.update({ 
      where: { id }, 
      data: dto 
    });
  }

  async remove(id: string) {
    await this.findOne(id); // Check if exists
    return this.prisma.station.delete({ where: { id } });
  }
}
