import { Injectable, NotFoundException } from '@nestjs/common';
import { Site } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CreateSiteDto } from './dto/create-site.dto';
import { UpdateSiteDto } from './dto/update-site.dto';

@Injectable()
export class SiteService {
  constructor(private readonly prisma: PrismaService) {}

  async create(agencyId: string, dto: CreateSiteDto): Promise<Site> {
    await this.ensureAgencyExists(agencyId);
    return this.prisma.site.create({ data: { ...dto, agencyId } });
  }

  async findAllByAgency(agencyId: string): Promise<Site[]> {
    await this.ensureAgencyExists(agencyId);
    return this.prisma.site.findMany({
      where: { agencyId },
      orderBy: { createdAt: 'desc' },
    });
  }

  async findOne(agencyId: string, id: string): Promise<Site> {
    const site = await this.prisma.site.findFirst({ where: { id, agencyId } });
    if (!site) {
      throw new NotFoundException(`Site #${id} introuvable pour cette agence`);
    }
    return site;
  }

  async update(agencyId: string, id: string, dto: UpdateSiteDto): Promise<Site> {
    await this.findOne(agencyId, id);
    return this.prisma.site.update({ where: { id }, data: dto });
  }

  async remove(agencyId: string, id: string): Promise<Site> {
    await this.findOne(agencyId, id);
    return this.prisma.site.delete({ where: { id } });
  }

  private async ensureAgencyExists(agencyId: string): Promise<void> {
    const agency = await this.prisma.agency.findUnique({ where: { id: agencyId } });
    if (!agency) {
      throw new NotFoundException(`Agence #${agencyId} introuvable`);
    }
  }
}
