import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Agency } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { CreateAgencyDto } from './dto/create-agency.dto';
import { UpdateAgencyDto } from './dto/update-agency.dto';

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

  async create(dto: CreateAgencyDto): Promise<Agency> {
    const existing = await this.prisma.agency.findFirst({
      where: { OR: [{ email: dto.email }, { slug: dto.slug }] },
    });
    if (existing) {
      throw new ConflictException('Une agence avec cet email ou ce slug existe déjà');
    }

    return this.prisma.agency.create({ data: dto });
  }

  async findAll(): Promise<Agency[]> {
    return this.prisma.agency.findMany({ orderBy: { createdAt: 'desc' } });
  }

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

  async update(id: string, dto: UpdateAgencyDto): Promise<Agency> {
    await this.findOne(id);
    return this.prisma.agency.update({ where: { id }, data: dto });
  }

  async remove(id: string): Promise<Agency> {
    await this.findOne(id);
    return this.prisma.agency.delete({ where: { id } });
  }
}
