import { ListingEntity } from '@modules/listings/domain/entities/listing.entity';
import { type IListingRepository } from '@modules/listings/domain/repositories/listing.repository';
import { Price } from '@modules/listings/domain/value-objects/price.vo';
import { ApproveListingCommand } from '../commands/approve-listing/approve-listing.command';
import { ApproveListingHandler } from '../commands/approve-listing/approve-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, 'agent-1',
  );
  listing.submitForReview();
  listing.clearDomainEvents();
  return listing;
}

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

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

    mockEventBus = { publish: vi.fn() };

    handler = new ApproveListingHandler(
      mockListingRepo as any,
      mockEventBus as any,
    );
  });

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

    const command = new ApproveListingCommand('listing-1', 'admin-1', 'Looks good');
    const result = await handler.execute(command);

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

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

    const command = new ApproveListingCommand('nonexistent', 'admin-1');

    await expect(handler.execute(command)).rejects.toThrow('Listing không tồn tại');
  });

  it('throws ValidationException when listing is not pending review', async () => {
    const price = Price.create(500_000_000n).unwrap();
    const listing = ListingEntity.createNew(
      'listing-1', 'prop-1', 'seller-1', 'SALE', price, 80,
    );
    listing.clearDomainEvents();
    mockListingRepo.findById.mockResolvedValue(listing);

    const command = new ApproveListingCommand('listing-1', 'admin-1');

    await expect(handler.execute(command)).rejects.toThrow(/trạng thái/);
  });
});
