import {
  CreationOptional,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  Model,
  NonAttribute,
  Sequelize,
} from "sequelize";
import { InvoiceModel } from "./invoice.model";
import {
  InvoiceParticipantAddress_Model,
  TCreationInvoiceParticipantAddress_Model,
} from "./invoiceParticipantAddress.mo.del";

export type TCreationInvoiceParticipant_Model = InferCreationAttributes<
  InvoiceParticipant_Model,
  { omit: "shippingAddress" | "billingAddress" | "invoice" }
> & {
  billingAddress: TCreationInvoiceParticipantAddress_Model;
  shippingAddress: TCreationInvoiceParticipantAddress_Model;
};

export class InvoiceParticipant_Model extends Model<
  InferAttributes<
    InvoiceParticipant_Model,
    { omit: "shippingAddress" | "billingAddress" | "invoice" }
  >,
  InferCreationAttributes<
    InvoiceParticipant_Model,
    { omit: "shippingAddress" | "billingAddress" | "invoice" }
  >
> {
  static associate(connection: Sequelize) {
    const { Invoice_Model, InvoiceParticipantAddress_Model, InvoiceParticipant_Model } =
      connection.models;

    InvoiceParticipant_Model.belongsTo(Invoice_Model, {
      as: "invoice",
      foreignKey: "invoice_id",
      onDelete: "CASCADE",
    });

    InvoiceParticipant_Model.hasOne(InvoiceParticipantAddress_Model, {
      as: "shippingAddress",
      foreignKey: "participant_id",
      onDelete: "CASCADE",
    });

    InvoiceParticipant_Model.hasOne(InvoiceParticipantAddress_Model, {
      as: "billingAddress",
      foreignKey: "participant_id",
      onDelete: "CASCADE",
    });
  }

  declare participant_id: string;
  declare invoice_id: string;
  declare tin: CreationOptional<string>;
  declare company_name: CreationOptional<string>;
  declare first_name: CreationOptional<string>;
  declare last_name: CreationOptional<string>;

  declare shippingAddress?: NonAttribute<InvoiceParticipantAddress_Model>;
  declare billingAddress?: NonAttribute<InvoiceParticipantAddress_Model>;

  declare invoice?: NonAttribute<InvoiceModel>;
}

export default (sequelize: Sequelize) => {
  InvoiceParticipant_Model.init(
    {
      participant_id: {
        type: new DataTypes.UUID(),
        primaryKey: true,
      },
      invoice_id: {
        type: new DataTypes.UUID(),
        primaryKey: true,
      },
      tin: {
        type: new DataTypes.STRING(),
        allowNull: true,
      },
      company_name: {
        type: new DataTypes.STRING(),
        allowNull: true,
      },
      first_name: {
        type: new DataTypes.STRING(),
        allowNull: true,
      },
      last_name: {
        type: new DataTypes.STRING(),
        allowNull: true,
      },
    },
    {
      sequelize,
      tableName: "invoice_participants",
      timestamps: false,
    }
  );

  return InvoiceParticipant_Model;
};
