import { DataTypes, InferAttributes, InferCreationAttributes, Model, Sequelize } from "sequelize";

export type DocNumberCreationAttributes = InferCreationAttributes<DocNumberModel, {}> & {};

export class DocNumberModel extends Model<
  InferAttributes<DocNumberModel>,
  InferCreationAttributes<DocNumberModel>
> {
  declare id: string; // UUID
  declare company_id: string;
  declare year: number; // 2025, 2026
  declare docType: string; // ej. "INVOICE"
  declare series: string | null; // ej. "2025", "Sucursal-01"
  declare currentValue: number; // último número asignado
  declare formatPattern: string; // ej. "{series}/{number:000000}"

  static associate(database: Sequelize) {}

  static hooks(database: Sequelize) {}
}

export default (database: Sequelize) => {
  DocNumberModel.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
      },
      company_id: {
        type: DataTypes.UUID,
        allowNull: false,
      },
      year: {
        type: DataTypes.SMALLINT(),
        allowNull: false,
      },
      docType: {
        type: DataTypes.STRING(),
        allowNull: false,
      },
      series: {
        type: DataTypes.STRING(),
        allowNull: true,
        defaultValue: null,
      },
      currentValue: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false,
        defaultValue: 0,
      },
      formatPattern: {
        type: DataTypes.STRING(),
        allowNull: false,
        defaultValue: "{series}/{number:000000}",
      },
    },
    {
      sequelize: database,
      tableName: "doc-numbers",

      underscored: true,
      paranoid: false, // no softs deletes
      timestamps: true,

      createdAt: "created_at",
      updatedAt: "updated_at",
      deletedAt: "deleted_at",

      indexes: [
        {
          unique: true,
          fields: ["company_id", "year", "docType", "series"],
        },
      ],

      whereMergeStrategy: "and", // <- cómo tratar el merge de un scope

      defaultScope: {},

      scopes: {},
    }
  );
  return DocNumberModel;
};
