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

// --- Quotes ---
const Quote = sequelize.define('Quote', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    quoteNumber: { type: DataTypes.STRING, unique: true, allowNull: false },
    status: {
        type: DataTypes.ENUM('Draft', 'Sent', 'Accepted', 'Rejected', 'Expired'),
        defaultValue: 'Draft'
    },
    issueDate: { type: DataTypes.DATEONLY, allowNull: false },
    expiryDate: { type: DataTypes.DATEONLY },
    subtotal: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    tax: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    discount: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    total: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    theme: { type: DataTypes.STRING, defaultValue: 'Professional' },
    notes: { type: DataTypes.TEXT },
    taxes: { type: DataTypes.JSON, defaultValue: [] }, // Document-level taxes: [{name, rate, amount}]
    createdBy: { type: DataTypes.UUID }
}, {
    tableName: 'Quotes',
    timestamps: true
});

const QuoteItem = sequelize.define('QuoteItem', {
    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 },
    taxRate: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 },
    taxAmount: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    lineTotal: { type: DataTypes.DECIMAL(15, 2), allowNull: false }
}, {
    tableName: 'QuoteItems',
    timestamps: false
});

// --- Invoices ---
const Invoice = sequelize.define('Invoice', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    invoiceNumber: { type: DataTypes.STRING, unique: true, allowNull: false },
    status: {
        type: DataTypes.ENUM('Draft', 'Sent', 'Paid', 'Overdue', 'Cancelled'),
        defaultValue: 'Draft'
    },
    issueDate: { type: DataTypes.DATEONLY, allowNull: false },
    dueDate: { type: DataTypes.DATEONLY, allowNull: false },
    subtotal: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    tax: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    discount: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    total: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    theme: { type: DataTypes.STRING, defaultValue: 'Professional' },
    balanceDue: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    source: { type: DataTypes.ENUM('Manual', 'Quote'), defaultValue: 'Manual' },
    quoteId: { type: DataTypes.UUID }, // Link to source quote if converted
    taxes: { type: DataTypes.JSON, defaultValue: [] }, // Document-level taxes: [{name, rate, amount}]
    createdBy: { type: DataTypes.UUID },
    // Recurring Billing Options
    isRecurring: { type: DataTypes.BOOLEAN, defaultValue: false },
    recurringFrequency: { type: DataTypes.ENUM('Weekly', 'Monthly', 'Quarterly', 'Yearly') },
    recurringInterval: { type: DataTypes.INTEGER, defaultValue: 1 },
    recurringStartDate: { type: DataTypes.DATEONLY },
    recurringEndDate: { type: DataTypes.DATEONLY },
    lastRecurringDate: { type: DataTypes.DATEONLY },
    nextRecurringDate: { type: DataTypes.DATEONLY }
}, {
    tableName: 'Invoices',
    timestamps: true
});

const InvoiceItem = sequelize.define('InvoiceItem', {
    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 },
    taxRate: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 },
    taxAmount: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    lineTotal: { type: DataTypes.DECIMAL(15, 2), allowNull: false }
}, {
    tableName: 'InvoiceItems',
    timestamps: false
});

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

Quote.hasMany(QuoteItem, { foreignKey: 'quoteId', as: 'items', onDelete: 'CASCADE' });
QuoteItem.belongsTo(Quote, { foreignKey: 'quoteId' });

Client.hasMany(Invoice, { foreignKey: 'clientId' });
Invoice.belongsTo(Client, { foreignKey: 'clientId' });

Invoice.hasMany(InvoiceItem, { foreignKey: 'invoiceId', as: 'items', onDelete: 'CASCADE' });
InvoiceItem.belongsTo(Invoice, { foreignKey: 'invoiceId' });

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

module.exports = { Quote, QuoteItem, Invoice, InvoiceItem };
