import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '@config/database';
import { Form16CreditNote } from './Form16CreditNote';
import { Form16DebitNote } from './Form16DebitNote';

export type Form16QuarterStatusValue = 'SETTLED' | 'DEBIT_ISSUED_PENDING_FORM16';

export interface Form16QuarterStatusAttributes {
  id: number;
  tanNumber: string;
  financialYear: string;
  quarter: string;
  status: Form16QuarterStatusValue;
  lastCreditNoteId?: number | null;
  lastDebitNoteId?: number | null;
  updatedAt: Date;
}

interface Form16QuarterStatusCreationAttributes
  extends Optional<
    Form16QuarterStatusAttributes,
    'id' | 'lastCreditNoteId' | 'lastDebitNoteId' | 'updatedAt'
  > {}

class Form16QuarterStatus
  extends Model<Form16QuarterStatusAttributes, Form16QuarterStatusCreationAttributes>
  implements Form16QuarterStatusAttributes
{
  public id!: number;
  public tanNumber!: string;
  public financialYear!: string;
  public quarter!: string;
  public status!: Form16QuarterStatusValue;
  public lastCreditNoteId?: number | null;
  public lastDebitNoteId?: number | null;
  public updatedAt!: Date;

  public lastCreditNote?: Form16CreditNote;
  public lastDebitNote?: Form16DebitNote;
}

Form16QuarterStatus.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    tanNumber: {
      type: DataTypes.STRING(20),
      allowNull: false,
      field: 'tan_number',
    },
    financialYear: {
      type: DataTypes.STRING(20),
      allowNull: false,
      field: 'financial_year',
    },
    quarter: {
      type: DataTypes.STRING(10),
      allowNull: false,
    },
    status: {
      type: DataTypes.STRING(50),
      allowNull: false,
    },
    lastCreditNoteId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'last_credit_note_id',
      references: { model: 'form_16_credit_notes', key: 'id' },
      onDelete: 'SET NULL',
    },
    lastDebitNoteId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'last_debit_note_id',
      references: { model: 'form_16_debit_notes', key: 'id' },
      onDelete: 'SET NULL',
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      field: 'updated_at',
    },
  },
  {
    sequelize,
    tableName: 'form_16_quarter_status',
    timestamps: true,
    underscored: true,
    updatedAt: 'updated_at',
    createdAt: false,
  }
);

Form16QuarterStatus.belongsTo(Form16CreditNote, {
  as: 'lastCreditNote',
  foreignKey: 'lastCreditNoteId',
  targetKey: 'id',
});
Form16QuarterStatus.belongsTo(Form16DebitNote, {
  as: 'lastDebitNote',
  foreignKey: 'lastDebitNoteId',
  targetKey: 'id',
});

export { Form16QuarterStatus };
