// controllers/tenantController.js
// Controller for tenant-related operations

// Mock tenant storage - this would be a database in production
const tenants = [
  {
    id: 'default',
    name: 'Default Tenant',
    subdomain: 'default',
    settings: {
      allowedDomains: ['localhost', 'merchants-of-hope.org'],
      features: ['job-posting', 'resume-uploading', 'application-tracking']
    },
    createdAt: new Date(),
    updatedAt: new Date()
  }
];

const getTenant = async (req, res) => {
  try {
    const { tenantId } = req.params;
    
    // Find the requested tenant
    const tenant = tenants.find(t => t.id === tenantId || t.subdomain === tenantId);
    
    if (!tenant) {
      return res.status(404).json({ error: 'Tenant not found' });
    }
    
    res.status(200).json({
      tenant: {
        id: tenant.id,
        name: tenant.name,
        subdomain: tenant.subdomain,
        settings: tenant.settings,
        createdAt: tenant.createdAt,
        updatedAt: tenant.updatedAt
      }
    });
  } catch (error) {
    console.error('Get tenant error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

const createTenant = async (req, res) => {
  try {
    const { name, subdomain, settings } = req.body;
    
    // Validate required fields
    if (!name || !subdomain) {
      return res.status(400).json({ error: 'Name and subdomain are required' });
    }
    
    // Check if tenant already exists
    const existingTenant = tenants.find(t => t.subdomain === subdomain || t.name === name);
    if (existingTenant) {
      return res.status(409).json({ error: 'Tenant with this name or subdomain already exists' });
    }
    
    // Create new tenant
    const newTenant = {
      id: require('uuid').v4(),
      name,
      subdomain,
      settings: settings || {},
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    tenants.push(newTenant);
    
    res.status(201).json({
      message: 'Tenant created successfully',
      tenant: {
        id: newTenant.id,
        name: newTenant.name,
        subdomain: newTenant.subdomain,
        settings: newTenant.settings
      }
    });
  } catch (error) {
    console.error('Create tenant error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

const updateTenant = async (req, res) => {
  try {
    const { tenantId } = req.params;
    const { name, settings } = req.body;
    
    // Find the tenant to update
    const tenantIndex = tenants.findIndex(t => t.id === tenantId || t.subdomain === tenantId);
    
    if (tenantIndex === -1) {
      return res.status(404).json({ error: 'Tenant not found' });
    }
    
    // Update tenant properties
    if (name) {
      tenants[tenantIndex].name = name;
    }
    if (settings) {
      tenants[tenantIndex].settings = { ...tenants[tenantIndex].settings, ...settings };
    }
    tenants[tenantIndex].updatedAt = new Date();
    
    res.status(200).json({
      message: 'Tenant updated successfully',
      tenant: {
        id: tenants[tenantIndex].id,
        name: tenants[tenantIndex].name,
        subdomain: tenants[tenantIndex].subdomain,
        settings: tenants[tenantIndex].settings,
        updatedAt: tenants[tenantIndex].updatedAt
      }
    });
  } catch (error) {
    console.error('Update tenant error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

const deleteTenant = async (req, res) => {
  try {
    const { tenantId } = req.params;
    
    // Find the tenant to delete
    const tenantIndex = tenants.findIndex(t => t.id === tenantId || t.subdomain === tenantId);
    
    if (tenantIndex === -1) {
      return res.status(404).json({ error: 'Tenant not found' });
    }
    
    // In a real implementation, you'd want to also delete all related data
    // For now, we'll just remove the tenant from our mock storage
    tenants.splice(tenantIndex, 1);
    
    res.status(200).json({
      message: 'Tenant deleted successfully'
    });
  } catch (error) {
    console.error('Delete tenant error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

module.exports = {
  getTenant,
  createTenant,
  updateTenant,
  deleteTenant
};