const { Staff } = require('../models/staff');
const { User, Role } = require('../models/foundation');
const { logAction } = require('../utils/logger');
const { generateSecurePassword } = require('../utils/passwordGenerator');
const { sendWelcomeEmail } = require('../services/notificationService');
const bcrypt = require('bcryptjs');

exports.createStaff = async (data, userId) => {
    // 1. Validate Email and Phone (Required)
    if (!data.email || !data.phone) {
        throw new Error('Both Email and Phone are required for Staff creation.');
    }

    // 2. Check if email already exists in User or Staff
    const existingUser = await User.findOne({ where: { email: data.email } });
    if (existingUser) {
        throw new Error('User with this email already exists.');
    }

    // 3. Generate or Use Custom Password
    const customPassword = data.customPassword ? String(data.customPassword).trim() : null;
    const plainPassword = customPassword || generateSecurePassword();
    const hashedPassword = await bcrypt.hash(plainPassword, 10);

    // 4. Create Staff Record
    const staff = await Staff.create(data);

    // 5. Ensure STAFF Role exists and Create User Record
    // Try to find 'STAFF' role, or default to a basic role if not found (or create it)
    let staffRole = await Role.findOne({ where: { constant: 'STAFF' } });
    if (!staffRole) {
        // Fallback or Create. For now, we create it if missing to ensure system works.
        staffRole = await Role.create({ name: 'Staff Member', constant: 'STAFF' });
    }

    const user = await User.create({
        fullName: data.fullName,
        email: data.email,
        password: hashedPassword,
        roleId: staffRole.id,
        isActive: true,
        mustChangePassword: true,
        // No staffId in User model typically, but email links them.
        clientId: null
    });

    console.log('User created with ID:', user.id, 'mustChangePassword:', user.mustChangePassword);

    // Send Welcome Email
    try {
        await sendWelcomeEmail(user, plainPassword);
        console.log('Welcome email sent to:', user.email);
    } catch (emailErr) {
        console.error('Failed to send welcome email:', emailErr);
        // Do not throw, allow creation to proceed
    }

    await logAction(userId, 'CREATE', 'STAFF', { id: staff.id, name: staff.fullName }, null);

    // Return staff and the generated password so it can be shown once
    return { ...staff.toJSON(), generatedPassword: plainPassword };
};

exports.getAllStaff = async (filters = {}) => {
    const where = {};
    if (filters.staffType) where.staffType = filters.staffType;
    if (filters.isActive !== undefined) where.isActive = filters.isActive;

    return await Staff.findAll({
        where,
        order: [['fullName', 'ASC']]
    });
};

exports.getStaffById = async (id) => {
    return await Staff.findByPk(id);
};

exports.updateStaff = async (id, data, userId) => {
    const staff = await Staff.findByPk(id);
    if (!staff) throw new Error('Staff member not found');

    await staff.update(data);
    await logAction(userId, 'UPDATE', 'STAFF', { id, ...data }, null);
    return staff;
};

exports.deleteStaff = async (id, userId) => {
    const staff = await Staff.findByPk(id);
    if (!staff) throw new Error('Staff member not found');

    // In a real system, we might want to check if they have payroll history
    // For now, we allow deletion as per requirement
    await staff.destroy();
    await logAction(userId, 'DELETE', 'STAFF', { id }, null);
};
