import { UniqueID } from "@/core/common/domain";
import {
  type ISequelizeMapper,
  type MapperParamsType,
  SequelizeMapper,
} from "@/core/common/infrastructure";
import { Result } from "@repo/rdx-utils";
import { TabContext } from "../../domain";
import { TabContextCreationAttributes, TabContextModel } from "../sequelize";

export interface ITabContextMapper
  extends ISequelizeMapper<TabContextModel, TabContextCreationAttributes, TabContext> {}

export class TabContextMapper
  extends SequelizeMapper<TabContextModel, TabContextCreationAttributes, TabContext>
  implements ITabContextMapper
{
  public mapToDomain(
    source: TabContextModel,
    params?: MapperParamsType
  ): Result<TabContext, Error> {
    // Crear Value Objects asegurando que sean válidos
    const uniqueIdResult = UniqueID.create(source.id);
    const tabIdResult = UniqueID.create(source.tab_id);
    const userIdResult = UniqueID.create(source.user_id);
    //const companyIdResult = UniqueID.create(entity.company_id, false);
    //const brachIdResult = UniqueID.create(entity.branch_id, false);

    // Validar que no haya errores en la creación de los Value Objects
    const okOrError = Result.combine([
      uniqueIdResult,
      tabIdResult,
      userIdResult,
      //companyIdResult,
      //brachIdResult,
    ]);
    if (okOrError.isFailure) {
      return Result.fail(okOrError.error.message);
    }

    // Crear el agregado de dominio
    return TabContext.create(
      {
        tabId: tabIdResult.data!,
        userId: userIdResult.data!,
        //companyId: companyIdResult.data,
        //branchId: brachIdResult.data,
      },
      uniqueIdResult.data!
    );
  }

  public mapToPersistence(
    source: TabContext,
    params?: MapperParamsType
  ): TabContextCreationAttributes {
    return {
      id: source.id.toString(),
      tab_id: source.tabId.toString(),
      user_id: source.userId.toString(),
    };
  }
}

const tabContextMapper: ITabContextMapper = new TabContextMapper();
export { tabContextMapper };
