import {
  MerchantStatus,
  Provider,
  ProviderMode,
} from "@prisma/client";
import * as bcrypt from "bcrypt";
import { EncryptionService } from "../../src/common/crypto/encryption.service";
import { newApiKeyValue, newId } from "../../src/common/ids/id.util";
import { PrismaService } from "../../src/prisma/prisma.service";

export interface SeededMerchant {
  merchantId: string;
  apiKey: string;
  apiKeyId: string;
  providerConfigId: string;
}

export interface SeedOptions {
  country?: string;
  provider?: Provider;
  mode?: ProviderMode;
  scope?: "full" | "restricted";
}

export async function seedMerchantWithApiKey(
  prisma: PrismaService,
  encryption: EncryptionService,
  opts: SeedOptions = {},
): Promise<SeededMerchant> {
  const country = opts.country ?? "PY";
  const provider = opts.provider ?? Provider.dlocal;
  const mode = opts.mode ?? ProviderMode.sandbox;

  const merchant = await prisma.merchant.create({
    data: {
      id: newId("merchant"),
      name: "Test Merchant",
      email: `merchant-${Date.now()}@test.local`,
      slug: `test-${Date.now()}`,
      defaultCountry: country,
      status: MerchantStatus.active,
    },
  });

  const { full, prefix } = newApiKeyValue("secret", "test");
  const hash = await bcrypt.hash(full, 4);
  const apiKey = await prisma.merchantApiKey.create({
    data: {
      id: newId("apiKey"),
      merchantId: merchant.id,
      type: "secret",
      environment: "test",
      prefix,
      hash,
      scope: opts.scope ?? "full",
      label: "e2e",
    },
  });

  const encrypted = encryption.encryptJson({
    xLogin: "fake_login",
    xTransKey: "fake_trans_key",
    secretKey: "fake_secret_key",
  });

  const providerConfig = await prisma.merchantProviderConfig.create({
    data: {
      id: newId("providerConfig"),
      merchantId: merchant.id,
      provider,
      country,
      mode,
      active: true,
      priority: 100,
      credentialsEncrypted: encrypted as unknown as object,
    },
  });

  return {
    merchantId: merchant.id,
    apiKey: full,
    apiKeyId: apiKey.id,
    providerConfigId: providerConfig.id,
  };
}
