import { Test } from "@nestjs/testing";
import { UnprocessableEntityException } from "@nestjs/common";

import { {{ module_class_name }}Module } from "../../../../src/modules/free/users/users_profiles/users-profiles.module";
import { {{ module_class_name }}Service } from "../../../../src/modules/free/users/users_profiles/users-profiles.service";

describe("{{ module_class_name }}Module Integration", () => {
  let service: {{ module_class_name }}Service;

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [{{ module_class_name }}Module],
    }).compile();

    service = moduleRef.get({{ module_class_name }}Service);
  });

  it("builds metadata from defaults", () => {
    const metadata = service.buildMetadata();
    expect(metadata.module).toBe("{{ module_name }}");
    expect(metadata.title).toBe("{{ module_title }}");
    expect(metadata.default_timezone).toBeDefined();
    expect(metadata.features).toContain("profile_management");
  });

  it("creates, updates, and lists profiles", async () => {
    const created = await service.upsertProfile("user-123", {
      displayName: "Ada Lovelace",
      socialLinks: ["https://example.com/ada"],
    });

    expect(created.userId).toBe("user-123");
    expect(created.timezone).toBeDefined();
    expect(created.marketingOptIn).toBe(true);

    const fetched = await service.getProfile("user-123");
    expect(fetched).toEqual(created);

    const updated = await service.upsertProfile("user-123", {
      biography: "Inventive mathematician",
    });

    expect(updated.biography).toBe("Inventive mathematician");
    expect(updated.displayName).toBe(created.displayName);

    const listed = await service.listProfiles();
    expect(listed).toEqual([updated]);
  });

  it("enforces validation limits", async () => {
    const metadata = service.buildMetadata();
    const tooLong = "x".repeat(metadata.max_bio_length + 1);

    await expect(
      service.upsertProfile("user-999", { biography: tooLong }),
    ).rejects.toBeInstanceOf(UnprocessableEntityException);

    const overflowingLinks = Array.from({ length: metadata.social_links_limit + 1 }, (_, index) => `https://example.com/${index}`);
    await expect(
      service.upsertProfile("user-999", { socialLinks: overflowingLinks }),
    ).rejects.toBeInstanceOf(UnprocessableEntityException);
  });

  it("deletes profiles", async () => {
    await service.upsertProfile("user-456", {});
    await service.deleteProfile("user-456");
    await expect(service.getProfile("user-456")).rejects.toThrow();
  });

  it("produces health payload", async () => {
    const payload = await service.resolveHealth();
    expect(payload.status).toBe("ok");
    expect(payload.features).toEqual(
      expect.arrayContaining(["profile_management"]),
    );
  });
});
