import { describe, expect, it, vi } from 'vitest';

import { LeagueMembership } from '@core/racing/domain/entities/LeagueMembership';

import { LeagueMembershipOrmEntity } from '../entities/LeagueMembershipOrmEntity';
import { LeagueMembershipOrmMapper } from './LeagueMembershipOrmMapper';

describe('LeagueMembershipOrmMapper', () => {
  it('toDomain preserves persisted identity and uses rehydrate semantics (does not call create)', () => {
    const mapper = new LeagueMembershipOrmMapper();

    const entity = new LeagueMembershipOrmEntity();
    entity.id = 'membership-1';
    entity.leagueId = '00000000-0000-4000-8000-000000000001';
    entity.driverId = '00000000-0000-4000-8000-000000000002';
    entity.role = 'member';
    entity.status = 'active';
    entity.joinedAt = new Date('2025-01-01T00:00:00.000Z');

    if (typeof (LeagueMembership as unknown as { rehydrate?: unknown }).rehydrate !== 'function') {
      throw new Error('rehydrate-missing');
    }

    const rehydrateSpy = vi.spyOn(
      LeagueMembership as unknown as { rehydrate: (...args: unknown[]) => unknown },
      'rehydrate',
    );
    const createSpy = vi.spyOn(LeagueMembership, 'create').mockImplementation(() => {
      throw new Error('create-called');
    });

    const domain = mapper.toDomain(entity);

    expect(domain.id).toBe(entity.id);
    expect(domain.leagueId.toString()).toBe(entity.leagueId);
    expect(domain.driverId.toString()).toBe(entity.driverId);
    expect(createSpy).not.toHaveBeenCalled();
    expect(rehydrateSpy).toHaveBeenCalled();
  });

  it('toDomain validates persisted shape and throws adapter-scoped error type', () => {
    const mapper = new LeagueMembershipOrmMapper();

    const entity = new LeagueMembershipOrmEntity();
    entity.id = 'membership-1';
    entity.leagueId = '00000000-0000-4000-8000-000000000001';
    entity.driverId = '00000000-0000-4000-8000-000000000002';
    entity.role = 123 as unknown as string;
    entity.status = 'active';
    entity.joinedAt = new Date('2025-01-01T00:00:00.000Z');

    try {
      mapper.toDomain(entity);
      throw new Error('expected-to-throw');
    } catch (error) {
      expect(error).toMatchObject({ name: 'InvalidLeagueMembershipSchemaError' });
    }
  });
});