import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { CreateServiceDto } from './dto/create-service.dto';
import { UpdateServiceDto } from './dto/update-service.dto';
import { ListServicesQuery } from './dto/list-services.query';

const NOT_FOUND = 'Service not found';

@Injectable()
export class ServicesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  /** Lists the tenant's services A to Z with how many leads use each, and optional active-only and search filters. */
  async list(ctx: RequestTenantContext, query: ListServicesQuery = {}) {
    const activeOnly = query.activeOnly === 'true' || query.activeOnly === '1';
    const search = query.search;
    const [services, usage] = await Promise.all([
      this.prisma.service.findMany({
        where: this.tenant.scopeWhere(ctx, {
          ...(activeOnly ? { isActive: true } : {}),
          ...(search ? { OR: [{ name: { contains: search } }, { description: { contains: search } }] } : {}),
        }),
        orderBy: { name: 'asc' },
      }),
      this.prisma.lead.groupBy({ by: ['serviceInterest'], where: this.tenant.scopeWhere(ctx, { serviceInterest: { not: null } }), _count: { _all: true } }),
    ]);
    const counts = new Map(usage.map((u) => [(u.serviceInterest ?? '').toLowerCase(), u._count._all]));
    return services.map((s) => ({ ...s, leadCount: counts.get(s.name.toLowerCase()) ?? 0 }));
  }

  /** Finds one service in the tenant or throws 404. */
  private async findOrThrow(ctx: RequestTenantContext, id: string) {
    const service = await this.prisma.service.findFirst({ where: this.tenant.scopeWhere(ctx, { id }) });
    if (!service) throw new NotFoundException(NOT_FOUND);
    return service;
  }

  /** Turns a unique-name violation into a readable 409; rethrows anything else. */
  private rethrowDuplicate(err: unknown, name: string): never {
    if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2002') {
      throw new ConflictException(`Service "${name}" already exists.`);
    }
    throw err;
  }

  /** Creates a service; names are unique per tenant, ignoring letter case. */
  async create(ctx: RequestTenantContext, dto: CreateServiceDto) {
    try {
      return await this.prisma.service.create({
        data: this.tenant.scopeCreate(ctx, { name: dto.name, description: dto.description ?? null, isActive: dto.isActive ?? true }),
      });
    } catch (err) {
      this.rethrowDuplicate(err, dto.name);
    }
  }

  /** Updates a service; a rename is applied to every lead using the old name in the same transaction. */
  async update(ctx: RequestTenantContext, id: string, dto: UpdateServiceDto) {
    const existing = await this.findOrThrow(ctx, id);
    const renamed = dto.name !== undefined && dto.name !== existing.name;
    try {
      return await this.prisma.$transaction(async (tx) => {
        if (renamed) {
          await tx.lead.updateMany({ where: this.tenant.scopeWhere(ctx, { serviceInterest: existing.name }), data: { serviceInterest: dto.name } });
        }
        await tx.service.updateMany({
          where: this.tenant.scopeWhere(ctx, { id }),
          data: {
            ...(dto.name !== undefined ? { name: dto.name } : {}),
            ...(dto.description !== undefined ? { description: dto.description } : {}),
            ...(dto.isActive !== undefined ? { isActive: dto.isActive } : {}),
          },
        });
        return tx.service.findFirstOrThrow({ where: this.tenant.scopeWhere(ctx, { id }) });
      });
    } catch (err) {
      this.rethrowDuplicate(err, dto.name ?? existing.name);
    }
  }

  /** Flips a service between active and inactive. */
  async toggleActive(ctx: RequestTenantContext, id: string) {
    const existing = await this.findOrThrow(ctx, id);
    await this.prisma.service.updateMany({ where: this.tenant.scopeWhere(ctx, { id }), data: { isActive: !existing.isActive } });
    return { ...existing, isActive: !existing.isActive };
  }

  /** Deletes a service only when no lead uses it; otherwise the admin should deactivate it. */
  async remove(ctx: RequestTenantContext, id: string) {
    const existing = await this.findOrThrow(ctx, id);
    const used = await this.prisma.lead.count({ where: this.tenant.scopeWhere(ctx, { serviceInterest: existing.name }) });
    if (used > 0) {
      throw new ConflictException(`"${existing.name}" is used by ${used} ${used === 1 ? 'lead' : 'leads'}. Deactivate it instead of deleting.`);
    }
    await this.prisma.service.deleteMany({ where: this.tenant.scopeWhere(ctx, { id }) });
    return { id };
  }
}
