"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable("Cards", {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
        allowNull: false,
      },
      customerId: {
        type: Sequelize.UUID,
        allowNull: false,
        references: { model: "Customers", key: "id" },
        onDelete: "CASCADE",
      },
      card_id: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
        comment: "Provider card reference from PayScribe",
      },
      brand: {
        type: Sequelize.ENUM("visa", "mastercard"),
        allowNull: false,
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false,
        comment: "Cardholder name as returned by provider",
      },
      card_number: {
        type: Sequelize.STRING,
        allowNull: true,
      },
      cvv: {
        type: Sequelize.STRING,
        allowNull: true,
      },
      expiry: {
        type: Sequelize.STRING,
        allowNull: true,
        comment: "e.g. 12/28",
      },
      balance: {
        type: Sequelize.DECIMAL(20, 2),
        defaultValue: 0.00,
        allowNull: false,
        comment: "Current card balance (local cache mirroring PayScribe)",
      },
      prev_balance: {
        type: Sequelize.DECIMAL(20, 2),
        defaultValue: 0.00,
        allowNull: false,
        comment: "Balance before the last transaction – used for audit trails",
      },
      currency: {
        type: Sequelize.STRING(10),
        defaultValue: "USD",
        allowNull: false,
      },
      status: {
        type: Sequelize.ENUM("active", "frozen", "terminated"),
        defaultValue: "active",
        allowNull: false,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal("NOW()"),
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal("NOW()"),
      },
    });

    await queryInterface.addIndex("Cards", ["customerId"], {
      name: "idx_cards_customerId",
    });
  },

  async down(queryInterface) {
    await queryInterface.dropTable("Cards");
  },
};
