import { Injectable, NotFoundException } from "@nestjs/common";
import * as bcrypt from "bcrypt";
import { newApiKeyValue, newId } from "../common/ids/id.util";
import { PrismaService } from "../prisma/prisma.service";
import type { CreateApiKeyDto } from "./dto/create-api-key.dto";

const BCRYPT_ROUNDS = 12;

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

  /**
   * Crea una API key y devuelve el valor completo SOLO esta vez.
   * El cliente debe guardarlo: no se puede recuperar después.
   */
  async create(merchantId: string, dto: CreateApiKeyDto) {
    const { full, prefix } = newApiKeyValue(
      dto.type === "secret" ? "secret" : "publishable",
      dto.environment === "live" ? "live" : "test",
    );
    const hash = await bcrypt.hash(full, BCRYPT_ROUNDS);

    const record = await this.prisma.merchantApiKey.create({
      data: {
        id: newId("apiKey"),
        merchantId,
        type: dto.type,
        environment: dto.environment,
        prefix,
        hash,
        scope: dto.scope ?? "full",
        label: dto.label ?? null,
      },
      select: {
        id: true,
        type: true,
        environment: true,
        prefix: true,
        scope: true,
        label: true,
        createdAt: true,
      },
    });

    return { ...record, secret: full };
  }

  async list(merchantId: string) {
    return this.prisma.merchantApiKey.findMany({
      where: { merchantId },
      select: {
        id: true,
        type: true,
        environment: true,
        prefix: true,
        scope: true,
        label: true,
        lastUsedAt: true,
        revokedAt: true,
        createdAt: true,
      },
      orderBy: { createdAt: "desc" },
    });
  }

  async revoke(merchantId: string, id: string) {
    const key = await this.prisma.merchantApiKey.findFirst({ where: { id, merchantId } });
    if (!key) throw new NotFoundException("API key not found");
    if (key.revokedAt) return key;

    return this.prisma.merchantApiKey.update({
      where: { id },
      data: { revokedAt: new Date() },
    });
  }
}
