const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');

const Client = sequelize.define('Client', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    // Basic Info
    name: { type: DataTypes.STRING, allowNull: false }, // "Customer Display Name"
    companyName: { type: DataTypes.STRING },
    customerNumber: { type: DataTypes.STRING, unique: true },
    email: { type: DataTypes.STRING, allowNull: false, unique: true },
    type: { type: DataTypes.ENUM('Business', 'Individual'), defaultValue: 'Business' },

    // Primary Contact
    salutation: { type: DataTypes.STRING },
    firstName: { type: DataTypes.STRING },
    lastName: { type: DataTypes.STRING },

    // Additional Contact
    phone: { type: DataTypes.STRING }, // Work Phone
    mobile: { type: DataTypes.STRING },
    website: { type: DataTypes.STRING },

    // Financial & Settings ("Other Details")
    currency: { type: DataTypes.STRING, defaultValue: 'KES' },
    openingBalance: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 },
    paymentTerms: { type: DataTypes.STRING, defaultValue: 'Due on Receipt' },
    portalLanguage: { type: DataTypes.STRING, defaultValue: 'English' },

    // Portal Control
    portalAccess: { type: DataTypes.BOOLEAN, defaultValue: false },

    billingAddress: { type: DataTypes.TEXT },
    shippingAddress: { type: DataTypes.TEXT },
    isActive: { type: DataTypes.BOOLEAN, defaultValue: true }
}, {
    tableName: 'Clients',
    timestamps: true
});

const ContactPerson = sequelize.define('ContactPerson', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    salutation: { type: DataTypes.STRING },
    firstName: { type: DataTypes.STRING },
    lastName: { type: DataTypes.STRING },
    email: { type: DataTypes.STRING },
    phone: { type: DataTypes.STRING },
    mobile: { type: DataTypes.STRING },
    clientId: { type: DataTypes.UUID }
}, {
    tableName: 'ContactPersons',
    timestamps: true
});

// Associations
Client.hasMany(ContactPerson, { foreignKey: 'clientId', as: 'contactPersons' });
ContactPerson.belongsTo(Client, { foreignKey: 'clientId' });

module.exports = { Client, ContactPerson };
