import { DataTypes } from "sequelize";

export default (sequelize) => {
  const Card = sequelize.define("Card", {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    customerId: {
      type: DataTypes.UUID,
      allowNull: false,
    },
    card_id: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      comment: "Provider card reference from PayScribe",
    },
    brand: {
      type: DataTypes.ENUM("visa", "mastercard"),
      allowNull: false,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: "Cardholder name as returned by provider",
    },
    card_number: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    cvv: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    expiry: {
      type: DataTypes.STRING,
      allowNull: true,
      comment: "e.g. 12/28",
    },
    balance: {
      type: DataTypes.DECIMAL(20, 2),
      defaultValue: 0.00,
      allowNull: false,
      comment: "Current card balance (local cache mirroring PayScribe)",
    },
    prev_balance: {
      type: DataTypes.DECIMAL(20, 2),
      defaultValue: 0.00,
      allowNull: false,
      comment: "Balance before the last transaction – used for audit trails",
    },
    currency: {
      type: DataTypes.STRING(10),
      defaultValue: "USD",
      allowNull: false,
    },
    status: {
      type: DataTypes.ENUM("active", "frozen", "terminated"),
      defaultValue: "active",
      allowNull: false,
    },
  }, {
    tableName: "Cards",
    timestamps: true,
  });

  Card.associate = (models) => {
    Card.belongsTo(models.Customer, {
      foreignKey: "customerId",
      as: "customer",
    });
  };

  return Card;
};
