import { MediaReference } from '@core/domain/media/MediaReference';
import { Driver } from '@core/racing/domain/entities/Driver';

import { DriverOrmEntity } from '../entities/DriverOrmEntity';
import { assertDate, assertNonEmptyString, assertOptionalStringOrNull } from '../schema/TypeOrmSchemaGuards';

export class DriverOrmMapper {
  toOrmEntity(domain: Driver): DriverOrmEntity {
    const entity = new DriverOrmEntity();
    entity.id = domain.id;
    entity.iracingId = domain.iracingId.toString();
    entity.name = domain.name.toString();
    entity.country = domain.country.toString();
    entity.bio = domain.bio?.toString() ?? null;
    entity.joinedAt = domain.joinedAt.toDate();
    entity.category = domain.category ?? null;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    entity.avatarRef = domain.avatarRef.toJSON() as any;
    return entity;
  }

  toDomain(entity: DriverOrmEntity): Driver {
    const entityName = 'Driver';

    assertNonEmptyString(entityName, 'id', entity.id);
    assertNonEmptyString(entityName, 'iracingId', entity.iracingId);
    assertNonEmptyString(entityName, 'name', entity.name);
    assertNonEmptyString(entityName, 'country', entity.country);
    assertDate(entityName, 'joinedAt', entity.joinedAt);
    assertOptionalStringOrNull(entityName, 'bio', entity.bio);
    assertOptionalStringOrNull(entityName, 'category', entity.category);

    const props: {
      id: string;
      iracingId: string;
      name: string;
      country: string;
      bio?: string;
      joinedAt: Date;
      category?: string;
      avatarRef?: MediaReference;
    } = {
      id: entity.id,
      iracingId: entity.iracingId,
      name: entity.name,
      country: entity.country,
      joinedAt: entity.joinedAt,
    };

    if (entity.bio !== null && entity.bio !== undefined) {
      props.bio = entity.bio;
    }
    if (entity.category !== null && entity.category !== undefined) {
      props.category = entity.category;
    }
    if (entity.avatarRef !== null && entity.avatarRef !== undefined) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      props.avatarRef = MediaReference.fromJSON(entity.avatarRef as any);
    }

    return Driver.rehydrate(props);
  }
}