import { DataTypes, Model } from 'sequelize';
import { sequelize } from '../config/database';

export class CoreDataWarehouse extends Model {
  public id!: string;
  public dataType!: string;
  public dataId!: string;
  public data!: string;
  public sourceSystem!: string;
  public syncStatus!: 'synced' | 'pending' | 'failed';
  public lastSyncAt!: Date;
  public nextSyncAt!: Date;
  public errorMessage?: string;
  public metadata!: string;
  public createdAt!: Date;
  public updatedAt!: Date;
}

CoreDataWarehouse.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    dataType: {
      type: DataTypes.STRING,
      allowNull: false,
      index: true,
    },
    dataId: {
      type: DataTypes.STRING,
      allowNull: false,
      index: true,
    },
    data: {
      type: DataTypes.TEXT,
      allowNull: false,
    },
    sourceSystem: {
      type: DataTypes.STRING,
      allowNull: false,
      index: true,
    },
    syncStatus: {
      type: DataTypes.ENUM('synced', 'pending', 'failed'),
      defaultValue: 'pending',
      allowNull: false,
    },
    lastSyncAt: {
      type: DataTypes.DATE,
      allowNull: true,
    },
    nextSyncAt: {
      type: DataTypes.DATE,
      allowNull: false,
      index: true,
    },
    errorMessage: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    metadata: {
      type: DataTypes.TEXT,
      allowNull: false,
      defaultValue: '{}',
    },
  },
  {
    sequelize,
    tableName: 'core_data_warehouse',
    timestamps: true,
    indexes: [
      {
        fields: ['dataType', 'dataId'],
        unique: true,
      },
      {
        fields: ['sourceSystem', 'syncStatus'],
      },
      {
        fields: ['nextSyncAt'],
      },
    ],
  }
);

export default CoreDataWarehouse;
