import { Avatar } from '@core/media/domain/entities/Avatar';
import { AvatarOrmEntity } from '../entities/AvatarOrmEntity';
import { TypeOrmMediaSchemaError } from '../errors/TypeOrmMediaSchemaError';
import {
  assertNonEmptyString,
  assertDate,
  assertBoolean,
} from '../schema/TypeOrmMediaSchemaGuards';

export class AvatarOrmMapper {
  toDomain(entity: AvatarOrmEntity): Avatar {
    const entityName = 'Avatar';

    try {
      assertNonEmptyString(entityName, 'id', entity.id);
      assertNonEmptyString(entityName, 'driverId', entity.driverId);
      assertNonEmptyString(entityName, 'mediaUrl', entity.mediaUrl);
      assertDate(entityName, 'selectedAt', entity.selectedAt);
      assertBoolean(entityName, 'isActive', entity.isActive);
    } catch (error) {
      if (error instanceof TypeOrmMediaSchemaError) {
        throw error;
      }
      const message = error instanceof Error ? error.message : 'Invalid persisted Avatar';
      throw new TypeOrmMediaSchemaError({ entityName, fieldName: 'unknown', reason: 'invalid_shape', message });
    }

    try {
      return Avatar.reconstitute({
        id: entity.id,
        driverId: entity.driverId,
        mediaUrl: entity.mediaUrl,
        selectedAt: entity.selectedAt,
        isActive: entity.isActive,
      });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Invalid persisted Avatar';
      throw new TypeOrmMediaSchemaError({ entityName, fieldName: 'unknown', reason: 'invalid_shape', message });
    }
  }

  toOrmEntity(avatar: Avatar): AvatarOrmEntity {
    const entity = new AvatarOrmEntity();
    const props = avatar.toProps();

    entity.id = props.id;
    entity.driverId = props.driverId;
    entity.mediaUrl = props.mediaUrl;
    entity.selectedAt = props.selectedAt;
    entity.isActive = props.isActive;

    return entity;
  }

  toStored(entity: AvatarOrmEntity): Avatar {
    return this.toDomain(entity);
  }
}
