const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');
const { Client } = require('./client');
const { User } = require('./foundation');

const Subscription = sequelize.define('Subscription', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    billingCycle: {
        type: DataTypes.ENUM('Monthly', 'Quarterly', 'Yearly'),
        defaultValue: 'Monthly'
    },
    startDate: { type: DataTypes.DATEONLY, allowNull: false },
    nextBillingDate: { type: DataTypes.DATEONLY, allowNull: false },
    endDate: { type: DataTypes.DATEONLY },
    amount: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    tax: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    status: {
        type: DataTypes.ENUM('Active', 'Paused', 'Cancelled', 'Suspended'),
        defaultValue: 'Active'
    },
    autoSendInvoice: { type: DataTypes.BOOLEAN, defaultValue: true },
    dueDays: { type: DataTypes.INTEGER, defaultValue: 7 }, // Days after billing date
    gracePeriod: { type: DataTypes.INTEGER, defaultValue: 5 }, // Days after due date before suspension
    creditBalance: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    createdBy: { type: DataTypes.UUID }
}, {
    tableName: 'Subscriptions',
    timestamps: true
});

const SubscriptionItem = sequelize.define('SubscriptionItem', {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    description: { type: DataTypes.STRING, allowNull: false },
    quantity: { type: DataTypes.DECIMAL(10, 2), allowNull: false },
    unitPrice: { type: DataTypes.DECIMAL(15, 2), allowNull: false },
    lineTotal: { type: DataTypes.DECIMAL(15, 2), allowNull: false }
}, {
    tableName: 'SubscriptionItems',
    timestamps: false
});

// Relations
Client.hasMany(Subscription, { foreignKey: 'clientId' });
Subscription.belongsTo(Client, { foreignKey: 'clientId' });

Subscription.hasMany(SubscriptionItem, { foreignKey: 'subscriptionId', as: 'items', onDelete: 'CASCADE' });
SubscriptionItem.belongsTo(Subscription, { foreignKey: 'subscriptionId' });

Subscription.belongsTo(User, { foreignKey: 'createdBy', as: 'creator' });

module.exports = { Subscription, SubscriptionItem };
