import { describe, test, expect, mock, beforeEach } from "bun:test";
import { buildMockCredentialType, buildMockConstants } from "../setup";

// ---------------------------------------------------------------------------
// Stable mock factory
// ---------------------------------------------------------------------------

function createStablePrismaMock(
  overrides: Record<string, Record<string, any>> = {},
) {
  return new Proxy(
    {},
    {
      get(_target, model: string) {
        if (model === "$connect" || model === "$disconnect")
          return mock(() => Promise.resolve());
        if (overrides[model]) return overrides[model];
        return new Proxy({}, { get: () => mock(() => Promise.resolve(null)) });
      },
    },
  );
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

describe("credentialTypes manager", () => {
  beforeEach(() => {
    mock.restore();
  });

  // -------------------------------------------------------------------
  // fetch
  // -------------------------------------------------------------------
  describe("fetch()", () => {
    test("returns CredentialTypeController when found", async () => {
      const mockData = { ...buildMockCredentialType(), credentials: [] };
      mock.module("../../src/constants", () =>
        buildMockConstants({
          prisma: createStablePrismaMock({
            credentialType: {
              findFirst: mock(() => Promise.resolve(mockData)),
            },
          }),
        }),
      );

      const { credentialTypes } =
        await import("../../src/managers/credentialTypes");
      const result = await credentialTypes.fetch("ctype-1");
      expect(result).toBeDefined();
      expect(result.id).toBe("ctype-1");
    });

    test("throws 404 when not found", async () => {
      mock.module("../../src/constants", () =>
        buildMockConstants({
          prisma: createStablePrismaMock({
            credentialType: {
              findFirst: mock(() => Promise.resolve(null)),
            },
          }),
        }),
      );

      const { credentialTypes } =
        await import("../../src/managers/credentialTypes");
      try {
        await credentialTypes.fetch("nonexistent");
        expect(true).toBe(false);
      } catch (e: any) {
        expect(e.name).toBe("CredentialTypeNotFound");
        expect(e.status).toBe(404);
      }
    });
  });

  // -------------------------------------------------------------------
  // fetchAll
  // -------------------------------------------------------------------
  describe("fetchAll()", () => {
    test("returns array of controllers", async () => {
      const items = [
        { ...buildMockCredentialType(), credentials: [] },
        {
          ...buildMockCredentialType({ id: "ctype-2", name: "API Key" }),
          credentials: [],
        },
      ];
      mock.module("../../src/constants", () =>
        buildMockConstants({
          prisma: createStablePrismaMock({
            credentialType: {
              findMany: mock(() => Promise.resolve(items)),
              findFirst: mock(() => Promise.resolve(null)),
            },
          }),
        }),
      );

      const { credentialTypes } =
        await import("../../src/managers/credentialTypes");
      const result = await credentialTypes.fetchAll();
      expect(result).toBeArrayOfSize(2);
    });
  });

  // -------------------------------------------------------------------
  // create
  // -------------------------------------------------------------------
  describe("create()", () => {
    test("creates and returns a CredentialTypeController", async () => {
      const created = {
        ...buildMockCredentialType(),
        credentials: [],
      };
      mock.module("../../src/constants", () =>
        buildMockConstants({
          prisma: createStablePrismaMock({
            credentialType: {
              findFirst: mock(() => Promise.resolve(null)), // no dupe
              create: mock(() => Promise.resolve(created)),
            },
          }),
        }),
      );

      const { credentialTypes } =
        await import("../../src/managers/credentialTypes");
      const result = await credentialTypes.create({
        name: "Login Credential",
        permissionScope: "credential.login",
        fields: [],
      });
      expect(result).toBeDefined();
      expect(result.name).toBe("Login Credential");
    });

    test("throws when name already exists", async () => {
      mock.module("../../src/constants", () =>
        buildMockConstants({
          prisma: createStablePrismaMock({
            credentialType: {
              findFirst: mock(() => Promise.resolve(buildMockCredentialType())),
            },
          }),
        }),
      );

      const { credentialTypes } =
        await import("../../src/managers/credentialTypes");
      try {
        await credentialTypes.create({
          name: "Login Credential",
          permissionScope: "credential.login",
          fields: [],
        });
        expect(true).toBe(false);
      } catch (e: any) {
        expect(e.name).toBe("CredentialTypeAlreadyExists");
        expect(e.status).toBe(400);
      }
    });
  });

  // -------------------------------------------------------------------
  // delete
  // -------------------------------------------------------------------
  describe("delete()", () => {
    test("deletes credential type by id", async () => {
      const deleteMock = mock(() => Promise.resolve({}));
      mock.module("../../src/constants", () =>
        buildMockConstants({
          prisma: createStablePrismaMock({
            credentialType: {
              delete: deleteMock,
              findFirst: mock(() => Promise.resolve(null)),
            },
          }),
        }),
      );

      const { credentialTypes } =
        await import("../../src/managers/credentialTypes");
      await credentialTypes.delete("ctype-1");
      expect(deleteMock).toHaveBeenCalledWith({ where: { id: "ctype-1" } });
    });
  });
});
