import { ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';
import { AuthenticatedUser } from '../../../common/decorators/current-user.decorator';

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

  private tenantGuard(user: AuthenticatedUser) {
    if (!user.isSuperAdmin && !user.tenantId) throw new ForbiddenException();
    return user.tenantId;
  }

  create(user: AuthenticatedUser, data: { name: string; legalId?: string; iban?: string; contact?: string }) {
    const tenantId = this.tenantGuard(user);
    if (!tenantId) throw new ForbiddenException();
    return this.prisma.supplier.create({ data: { tenantId, ...data } });
  }

  list(user: AuthenticatedUser) {
    return this.prisma.supplier.findMany({
      where: user.isSuperAdmin ? {} : { tenantId: user.tenantId ?? '__none__' },
      orderBy: { name: 'asc' },
    });
  }

  async findOne(user: AuthenticatedUser, id: string) {
    const s = await this.prisma.supplier.findUnique({ where: { id } });
    if (!s) throw new NotFoundException('Supplier not found');
    if (!user.isSuperAdmin && s.tenantId !== user.tenantId) throw new ForbiddenException();
    return s;
  }

  async update(user: AuthenticatedUser, id: string, data: { name?: string; legalId?: string; iban?: string; contact?: string }) {
    await this.findOne(user, id);
    return this.prisma.supplier.update({ where: { id }, data });
  }

  async remove(user: AuthenticatedUser, id: string) {
    await this.findOne(user, id);
    await this.prisma.supplier.delete({ where: { id } });
    return { deleted: true };
  }
}
