import { DataTypes, Model, Optional, Sequelize } from 'sequelize';

export interface TransactionAttributes extends Optional<TransactionInterface, 'id'> {}

export class Transaction extends Model<TransactionInterface, TransactionAttributes> implements TransactionInterface {
    public id!: number;
    public externalOrderId!: string | null;
    public subscriptionId!: number | null;
    public userId!: number;
    public externalPaymentId!: string;
    public amount!: number;
    public currency!: string;
    public status!: number;
    public paidAt!: Date;
    public gateway!: string;
    public metaData!: object;
    public planData!: object | null;
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

    static initModel(sequelize: Sequelize): typeof Transaction {
        Transaction.init({
            id: { type: DataTypes.BIGINT, autoIncrement: true, primaryKey: true, comment: "Unique numeric identifier for the transaction record" },
            externalOrderId: { type: DataTypes.STRING, allowNull: true, unique: 'unique-transaction', comment: "Order ID from payment gateway (Razorpay order_id)" },
            subscriptionId: { type: DataTypes.BIGINT, allowNull: true, comment: "ID of the subscription this transaction belongs to" },
            userId: { type: DataTypes.BIGINT, allowNull: false, comment: "ID of the user who owns this transaction" },
            externalPaymentId: { type: DataTypes.STRING, allowNull: true, comment: "Payment ID from payment gateway (Razorpay payment.id)" },
            amount: { type: DataTypes.DECIMAL(10, 2), allowNull: false, comment: "Amount in smallest currency unit" },
            currency: { type: DataTypes.STRING(10), allowNull: false, defaultValue: "usd", comment: "Currency code in ISO 4217 format" },
            status: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: "0 = pending, 1 = paid, 2 = failed, 3 = refunded" },
            paidAt: { type: DataTypes.DATE, allowNull: true, comment: "Timestamp when invoice was paid" },
            gateway: { type: DataTypes.STRING, allowNull: false, defaultValue: process.env.PAYMENT_GATEWAY, comment: "Payment gateway type (razorpay)" },
            metaData: { type: DataTypes.JSON, allowNull: true, comment: "Additional metadata from the payment gateway" },
            planData: {type: DataTypes.JSON, allowNull: true, comment: "planObject" },
        }, 
        { 
            paranoid: true, 
            underscored: true, 
            sequelize, 
            tableName: 'transactions', 
            timestamps: true, 
            indexes: [
           
            
            ]
        });
        return Transaction;
    }

    public static associate(models: any) {
        // Define associations here if needed
        Transaction.belongsTo(models.User, { foreignKey: 'userId', as: 'author' });
    }
}
