import {
  CreationOptional,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  Model,
  NonAttribute,
  Sequelize,
} from "sequelize";
import { CustomerInvoiceModel } from "./customer-invoice.model";

export type CustomerInvoiceItemCreationAttributes = InferCreationAttributes<
  CustomerInvoiceItemModel,
  { omit: "invoice" }
>;

export class CustomerInvoiceItemModel extends Model<
  InferAttributes<CustomerInvoiceItemModel, { omit: "invoice" }>,
  InferCreationAttributes<CustomerInvoiceItemModel, { omit: "invoice" }>
> {
  static associate(connection: Sequelize) {
    const { CustomerInvoiceModel, CustomerInvoiceItemModel } = connection.models;

    CustomerInvoiceItemModel.belongsTo(CustomerInvoiceModel, {
      as: "invoice",
      foreignKey: "id",
      onDelete: "CASCADE",
    });
  }

  declare customer_invoice_id: string;
  declare item_id: string;
  declare id_article: CreationOptional<number>;
  declare position: number;
  declare description: CreationOptional<string>;
  declare quantity: CreationOptional<number>;
  declare unit_price: CreationOptional<number>;
  declare subtotal_price: CreationOptional<number>;
  declare discount: CreationOptional<number>;
  declare total_price: CreationOptional<number>;

  declare invoice: NonAttribute<CustomerInvoiceModel>;
}

export default (sequelize: Sequelize) => {
  CustomerInvoiceItemModel.init(
    {
      item_id: {
        type: new DataTypes.UUID(),
        primaryKey: true,
      },
      customer_invoice_id: {
        type: new DataTypes.UUID(),
        primaryKey: true,
      },
      id_article: {
        type: DataTypes.BIGINT().UNSIGNED,
        allowNull: true,
        defaultValue: null,
      },
      position: {
        type: new DataTypes.MEDIUMINT(),
        autoIncrement: false,
        allowNull: false,
      },
      description: {
        type: new DataTypes.TEXT(),
        allowNull: true,
        defaultValue: null,
      },
      quantity: {
        type: DataTypes.BIGINT(),
        allowNull: true,
        defaultValue: null,
      },
      unit_price: {
        type: new DataTypes.BIGINT(),
        allowNull: true,
        defaultValue: null,
      },
      subtotal_price: {
        type: new DataTypes.BIGINT(),
        allowNull: true,
        defaultValue: null,
      },
      discount: {
        type: new DataTypes.SMALLINT(),
        allowNull: true,
        defaultValue: null,
      },
      total_price: {
        type: new DataTypes.BIGINT(),
        allowNull: true,
        defaultValue: null,
      },
    },
    {
      sequelize,
      tableName: "customer_invoice_items",
      timestamps: false,

      indexes: [],
    }
  );

  return CustomerInvoiceItemModel;
};
