import { ListingEntity } from '@modules/listings/domain/entities/listing.entity';
import { type IListingRepository } from '@modules/listings/domain/repositories/listing.repository';
import { ModerationService } from '@modules/listings/domain/services/moderation.service';
import { Price } from '@modules/listings/domain/value-objects/price.vo';
import { ModerateListingCommand } from '../commands/moderate-listing/moderate-listing.command';
import { ModerateListingHandler } from '../commands/moderate-listing/moderate-listing.handler';

function createPendingListing(id = 'listing-1'): ListingEntity {
  const price = Price.create(1_000_000_000n).unwrap();
  const listing = ListingEntity.createNew(id, 'prop-1', 'seller-1', 'SALE', price, 100);
  listing.submitForReview();
  listing.clearDomainEvents();
  return listing;
}

describe('ModerateListingHandler', () => {
  let handler: ModerateListingHandler;
  let mockListingRepo: { [K in keyof IListingRepository]: ReturnType<typeof vi.fn> };
  let mockEventBus: { publish: ReturnType<typeof vi.fn> };
  let mockCache: { invalidate: ReturnType<typeof vi.fn>; invalidateByPrefix: ReturnType<typeof vi.fn> };

  beforeEach(() => {
    mockListingRepo = {
      findById: vi.fn(),
      findByIdWithProperty: vi.fn(),
      save: vi.fn(),
      update: vi.fn().mockResolvedValue(undefined),
      search: vi.fn(),
      findByStatus: vi.fn(),
      findBySellerId: vi.fn(),
    };

    mockEventBus = { publish: vi.fn() };
    mockCache = {
      invalidate: vi.fn().mockResolvedValue(undefined),
      invalidateByPrefix: vi.fn().mockResolvedValue(undefined),
    };

    handler = new ModerateListingHandler(
      mockListingRepo as any,
      mockEventBus as any,
      mockCache as any,
      new ModerationService(),
    );
  });

  it('approves a pending listing', async () => {
    const listing = createPendingListing();
    mockListingRepo.findById.mockResolvedValue(listing);

    const command = new ModerateListingCommand('listing-1', 'mod-1', 'approve');
    const result = await handler.execute(command);

    expect(result.status).toBe('ACTIVE');
    expect(mockListingRepo.update).toHaveBeenCalledTimes(1);
    expect(mockEventBus.publish).toHaveBeenCalled();
  });

  it('rejects a pending listing', async () => {
    const listing = createPendingListing();
    mockListingRepo.findById.mockResolvedValue(listing);

    const command = new ModerateListingCommand('listing-1', 'mod-1', 'reject', undefined, 'Nội dung không phù hợp');
    const result = await handler.execute(command);

    expect(result.status).toBe('REJECTED');
    expect(mockListingRepo.update).toHaveBeenCalledTimes(1);
  });

  it('sets moderation score before action', async () => {
    const listing = createPendingListing();
    mockListingRepo.findById.mockResolvedValue(listing);

    const command = new ModerateListingCommand('listing-1', 'mod-1', 'approve', 95, 'Chất lượng tốt');
    await handler.execute(command);

    expect(listing.moderationScore).toBe(95);
  });

  it('throws NotFoundException when listing does not exist', async () => {
    mockListingRepo.findById.mockResolvedValue(null);

    const command = new ModerateListingCommand('nonexistent', 'mod-1', 'approve');

    await expect(handler.execute(command)).rejects.toThrow('Listing');
  });

  it('invalidates cache after moderation', async () => {
    const listing = createPendingListing();
    mockListingRepo.findById.mockResolvedValue(listing);

    const command = new ModerateListingCommand('listing-1', 'mod-1', 'approve');
    await handler.execute(command);

    expect(mockCache.invalidate).toHaveBeenCalled();
    expect(mockCache.invalidateByPrefix).toHaveBeenCalled();
  });
});
