/**
 * User ORM Mapper
 *
 * Maps between User domain entity and UserOrmEntity
 */

import { User, UserProps } from '@domain/entities/user.entity';
import { toLocale } from '@domain/value-objects/locale.vo';
import { UserOrmEntity } from '../entities/user.orm-entity';

export class UserOrmMapper {
  /**
   * Map domain entity to ORM entity
   */
  static toOrm(domain: User): UserOrmEntity {
    const orm = new UserOrmEntity();
    const props = domain.toObject();

    orm.id = props.id;
    orm.organizationId = props.organizationId;
    orm.email = props.email;
    orm.passwordHash = props.passwordHash;
    orm.role = props.role;
    orm.firstName = props.firstName;
    orm.lastName = props.lastName;
    orm.phoneNumber = props.phoneNumber || null;
    orm.totpSecret = props.totpSecret || null;
    orm.isEmailVerified = props.isEmailVerified;
    orm.isActive = props.isActive;
    orm.lastLoginAt = props.lastLoginAt || null;
    orm.preferredLanguage = props.preferredLanguage;
    orm.createdAt = props.createdAt;
    orm.updatedAt = props.updatedAt;

    return orm;
  }

  /**
   * Map ORM entity to domain entity
   */
  static toDomain(orm: UserOrmEntity): User {
    const props: UserProps = {
      id: orm.id,
      organizationId: orm.organizationId,
      email: orm.email,
      passwordHash: orm.passwordHash,
      role: orm.role as any,
      firstName: orm.firstName,
      lastName: orm.lastName,
      phoneNumber: orm.phoneNumber || undefined,
      totpSecret: orm.totpSecret || undefined,
      isEmailVerified: orm.isEmailVerified,
      isActive: orm.isActive,
      lastLoginAt: orm.lastLoginAt || undefined,
      preferredLanguage: toLocale(orm.preferredLanguage),
      createdAt: orm.createdAt,
      updatedAt: orm.updatedAt,
    };

    return User.fromPersistence(props);
  }

  /**
   * Map array of ORM entities to domain entities
   */
  static toDomainMany(orms: UserOrmEntity[]): User[] {
    return orms.map(orm => this.toDomain(orm));
  }
}
