import "reflect-metadata";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { NoopTracer, NoopLogger } from "@repo/core-shared/instrumentation";
import { RecordingEventBus, RecordingJobQueue } from "@repo/core-testing/instrumentation";
import { bindDevSeedMedia } from "@/di/bind-dev-seed";
import { mediaContainer } from "@/di/container";
import { MEDIA_SYMBOLS } from "@/di/symbols";
import { MockMediaRepository } from "@/infrastructure/repositories/media.repository.mock";
import type { IMediaRepository } from "@/application/repositories/media.repository.interface";

const noop = { tracer: new NoopTracer(), logger: new NoopLogger() };

describe("bindDevSeedMedia", () => {
  // Each test starts from the default empty-mock binding and tears down
  // afterwards so the global mediaContainer state stays clean for siblings.
  beforeEach(() => {
    if (mediaContainer.isBound(MEDIA_SYMBOLS.IMediaRepository)) {
      mediaContainer.unbind(MEDIA_SYMBOLS.IMediaRepository);
    }
    mediaContainer
      .bind<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository)
      .to(MockMediaRepository);
  });

  afterEach(() => {
    if (mediaContainer.isBound(MEDIA_SYMBOLS.IMediaRepository)) {
      mediaContainer.unbind(MEDIA_SYMBOLS.IMediaRepository);
    }
    mediaContainer
      .bind<IMediaRepository>(MEDIA_SYMBOLS.IMediaRepository)
      .to(MockMediaRepository);
  });

  it("populates the repository with the dev media entries", async () => {
    await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });

    const repo = mediaContainer.get<IMediaRepository>(
      MEDIA_SYMBOLS.IMediaRepository,
    );
    const all = await repo.listMedia();

    expect(all.length).toBeGreaterThan(0);
  });

  it("seeds placeholder-1 reachable by id", async () => {
    await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });

    const repo = mediaContainer.get<IMediaRepository>(
      MEDIA_SYMBOLS.IMediaRepository,
    );
    const item = await repo.getMedia("placeholder-1");

    expect(item).toBeDefined();
    expect(item?.url).toBe("/dev/placeholder-1.jpg");
    expect(item?.alt).toBe("Hero background image");
  });

  it("is idempotent — calling twice rebuilds a fresh populated repo", async () => {
    await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
    const before = mediaContainer.get<IMediaRepository>(
      MEDIA_SYMBOLS.IMediaRepository,
    );
    const beforeCount = (await before.listMedia()).length;

    await bindDevSeedMedia({ ...noop, bus: new RecordingEventBus(), queue: new RecordingJobQueue() });
    const after = mediaContainer.get<IMediaRepository>(
      MEDIA_SYMBOLS.IMediaRepository,
    );
    const afterCount = (await after.listMedia()).length;

    expect(afterCount).toBe(beforeCount);
    // It's a fresh instance — not the previous one.
    expect(after).not.toBe(before);
  });
});
