/**
 * Super Admin Plan Controller
 * Manages subscription plans
 */

const BaseController = require('./BaseController');
const { pool } = require('../config/database');
const { logger } = require('../config/logger');
const i18n = require('../services/TranslationService');

class SuperAdminPlanController extends BaseController {
  /**
   * Get all subscription plans
   * GET /api/superadmin/plans
   */
  static async getAllPlans(req, res) {
    try {
      const [plans] = await pool.execute(
        `SELECT 
           sp.*,
           (SELECT COUNT(*) FROM tenants t WHERE t.plan_id = sp.id AND t.id != 0) AS tenant_count
         FROM subscription_plans sp
         ORDER BY sp.sort_order, sp.price`
      );

      return res.json({
        success: true,
        data: plans
      });
    } catch (error) {
      logger.error('Error getting plans', { error: error.message });
      return res.status(500).json({
        success: false,
        message: 'Error loading plans'
      });
    }
  }

  /**
   * Get plan by ID
   * GET /api/superadmin/plans/:id
   */
  static async getPlanById(req, res) {
    try {
      const { id } = req.params;

      const [plans] = await pool.execute(
        'SELECT * FROM subscription_plans WHERE id = ?',
        [id]
      );

      if (plans.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Plan not found'
        });
      }

      return res.json({
        success: true,
        data: plans[0]
      });
    } catch (error) {
      logger.error('Error getting plan', { error: error.message });
      return res.status(500).json({
        success: false,
        message: 'Error loading plan'
      });
    }
  }

  /**
   * Create new subscription plan
   * POST /api/superadmin/plans
   */
  static async createPlan(req, res) {
    try {
      console.log('=== CREATE PLAN DEBUG ===');
      console.log('Body:', JSON.stringify(req.body, null, 2));
      console.log('Content-Type:', req.headers['content-type']);
      
      logger.info('Creating plan - Request details:', { 
        body: req.body,
        headers: req.headers['content-type'],
        method: req.method
      });

      // Extract and convert values
      const name = req.body.name;
      const description = req.body.description;
      const price = req.body.price !== undefined ? parseFloat(req.body.price) : undefined;
      const currency = req.body.currency;
      const billing_period = req.body.billing_period || 'monthly';
      const max_stores = parseInt(req.body.max_stores) || 1;
      const max_users = parseInt(req.body.max_users) || 5;
      const max_departments = parseInt(req.body.max_departments) || 5;
      const max_contacts = parseInt(req.body.max_contacts) || 1000;
      const max_devices = parseInt(req.body.max_devices) || 1;
      const max_whatsapp_instances = parseInt(req.body.max_whatsapp_instances) || 1;
      const max_conversations = parseInt(req.body.max_conversations) || 1000;
      const max_messages_per_month = parseInt(req.body.max_messages_per_month) || 10000;
      const max_faqs = parseInt(req.body.max_faqs) || 10;
      const max_contact_groups = parseInt(req.body.max_contact_groups) || 10;
      const whatsapp_enabled = req.body.whatsapp_enabled === true || req.body.whatsapp_enabled === 'true';
      const ai_enabled = req.body.ai_enabled === true || req.body.ai_enabled === 'true';
      const woocommerce_enabled = req.body.woocommerce_enabled === true || req.body.woocommerce_enabled === 'true';
      const analytics_enabled = req.body.analytics_enabled === true || req.body.analytics_enabled === 'true';
      const priority_support_enabled = req.body.priority_support_enabled === true || req.body.priority_support_enabled === 'true';
      const api_access_enabled = req.body.api_access_enabled === true || req.body.api_access_enabled === 'true';
      const custom_branding_enabled = req.body.custom_branding_enabled === true || req.body.custom_branding_enabled === 'true';
      const invoices_enabled = req.body.invoices_enabled === true || req.body.invoices_enabled === 'true';
      const max_invoices_per_month = parseInt(req.body.max_invoices_per_month) || 0;
      const quotes_enabled = req.body.quotes_enabled === true || req.body.quotes_enabled === 'true';
      const max_quotes_per_month = parseInt(req.body.max_quotes_per_month) || 0;
      const widgets_enabled = req.body.widgets_enabled === true || req.body.widgets_enabled === 'true';
      const max_widgets = parseInt(req.body.max_widgets) || 0;
      const payment_links_enabled = req.body.payment_links_enabled === true || req.body.payment_links_enabled === 'true';
      const max_payment_links_per_month = parseInt(req.body.max_payment_links_per_month) || 0;
      const max_email_accounts = parseInt(req.body.max_email_accounts) || 0;
      const max_emails_per_month = parseInt(req.body.max_emails_per_month) || 0;
      const max_omnichannel_accounts = parseInt(req.body.max_omnichannel_accounts) || 0;
      
      // Bio Link fields
      const biolink_enabled = req.body.biolink_enabled === true || req.body.biolink_enabled === 'true';
      const max_bio_pages = parseInt(req.body.max_bio_pages) || 0;
      const max_short_links = parseInt(req.body.max_short_links) || 0;
      const max_file_transfers = parseInt(req.body.max_file_transfers) || 0;
      const max_vcards = parseInt(req.body.max_vcards) || 0;
      const max_event_links = parseInt(req.body.max_event_links) || 0;
      const max_html_pages = parseInt(req.body.max_html_pages) || 0;
      const max_qr_codes = parseInt(req.body.max_qr_codes) || 0;
      
      const pix_enabled = req.body.pix_enabled === true || req.body.pix_enabled === 'true';
      const cash_enabled = req.body.cash_enabled === true || req.body.cash_enabled === 'true';
      
      const is_trial = req.body.is_trial === true || req.body.is_trial === 'true';
      const trial_days = parseInt(req.body.trial_days) || 0;
      const is_free = req.body.is_free === true || req.body.is_free === 'true';
      const stripe_price_id = req.body.stripe_price_id;
      const paypal_plan_id = req.body.paypal_plan_id;
      const sort_order = parseInt(req.body.sort_order) || 0;

      logger.info('Extracted values:', { name, price, priceType: typeof price });
      console.log('=== EXTRACTED VALUES ===');
      console.log('Name:', name);
      console.log('Price:', price, 'Type:', typeof price);
      console.log('Is NaN:', isNaN(price));

      // Validation
      if (!name || price === undefined || isNaN(price)) {
        logger.warn('Plan creation validation failed', { 
          name, 
          price, 
          nameExists: !!name, 
          priceExists: price !== undefined,
          priceIsNaN: isNaN(price)
        });
        return res.status(400).json({
          success: false,
          message: 'Name and valid price are required',
          debug: {
            name: name || 'missing',
            price: price === undefined ? 'undefined' : price,
            priceIsNaN: isNaN(price)
          }
        });
      }

      // Check if only one free plan exists
      if (is_free) {
        const [freePlans] = await pool.execute(
          'SELECT id, name FROM subscription_plans WHERE is_free = TRUE'
        );
        if (freePlans.length > 0) {
          logger.warn('Attempt to create second free plan', { existingPlan: freePlans[0] });
          return res.status(400).json({
            success: false,
            message: `Only one free plan is allowed. A free plan already exists: "${freePlans[0].name}". Please uncheck "Free Plan" or edit the existing free plan.`
          });
        }
      }

      let resolvedCurrency = currency;
      if (!resolvedCurrency) {
        const [defaultCurrencyRows] = await pool.execute(
          'SELECT code FROM currencies WHERE is_default = TRUE AND active = TRUE ORDER BY id LIMIT 1'
        );
        resolvedCurrency = defaultCurrencyRows?.[0]?.code || 'USD';
      }

      const [result] = await pool.execute(
        `INSERT INTO subscription_plans (
          name, description, price, currency, billing_period,
          max_stores, max_users, max_departments, max_contacts, max_devices, max_whatsapp_instances,
          max_whatsapp_cloud_accounts,
          max_conversations, max_messages_per_month, max_contact_groups, max_faqs,
          max_widgets, max_invoices_per_month, max_quotes_per_month, max_payment_links_per_month,
          max_email_accounts, max_emails_per_month, max_omnichannel_accounts,
          whatsapp_enabled, ai_enabled, woocommerce_enabled, analytics_enabled,
          priority_support_enabled, api_access_enabled, custom_branding_enabled,
          invoices_enabled, quotes_enabled, widgets_enabled, payment_links_enabled,
          biolink_enabled, max_bio_pages, max_short_links, max_file_transfers,
          max_vcards, max_event_links, max_html_pages, max_qr_codes,
          pix_enabled, cash_enabled,
          is_trial, trial_days, is_free,
          stripe_price_id, paypal_plan_id, sort_order
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          name, description, price, resolvedCurrency, billing_period,
          max_stores, max_users, max_departments, max_contacts, max_devices, max_whatsapp_instances,
          max_whatsapp_instances, // Use same value as max_whatsapp_instances by default
          max_conversations, max_messages_per_month, max_contact_groups, max_faqs,
          max_widgets, max_invoices_per_month, max_quotes_per_month, max_payment_links_per_month,
          max_email_accounts, max_emails_per_month, max_omnichannel_accounts,
          whatsapp_enabled, ai_enabled, woocommerce_enabled, analytics_enabled,
          priority_support_enabled, api_access_enabled, custom_branding_enabled,
          invoices_enabled, quotes_enabled, widgets_enabled, payment_links_enabled,
          biolink_enabled, max_bio_pages, max_short_links, max_file_transfers,
          max_vcards, max_event_links, max_html_pages, max_qr_codes,
          pix_enabled, cash_enabled,
          is_trial, trial_days, is_free,
          stripe_price_id, paypal_plan_id, sort_order
        ]
      );

      logger.info('Plan created', { planId: result.insertId, name });

      return res.status(201).json({
        success: true,
        message: 'Plan created successfully',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('Error creating plan', { 
        error: error.message, 
        stack: error.stack,
        sqlMessage: error.sqlMessage,
        sqlState: error.sqlState,
        errno: error.errno,
        sql: error.sql
      });
      
      console.error('=== ERROR DETAILS ===');
      console.error('Message:', error.message);
      console.error('SQL:', error.sql);
      console.error('SQL Message:', error.sqlMessage);
      
      // Check for specific SQL errors
      if (error.errno === 1054) {
        return res.status(500).json({
          success: false,
          message: 'Database schema error: Unknown column',
          details: error.sqlMessage
        });
      }
      
      return res.status(500).json({
        success: false,
        message: 'Error creating plan',
        details: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  }

  /**
   * Update subscription plan
   * PUT /api/superadmin/plans/:id
   */
  static async updatePlan(req, res) {
    try {
      const { id } = req.params;
      const updates = req.body;

      // Check if plan exists
      const [existingPlan] = await pool.execute(
        'SELECT * FROM subscription_plans WHERE id = ?',
        [id]
      );

      if (existingPlan.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Plan not found'
        });
      }

      // Check free plan constraint
      if (updates.is_free && !existingPlan[0].is_free) {
        const [freePlans] = await pool.execute(
          'SELECT id FROM subscription_plans WHERE is_free = TRUE AND id != ?',
          [id]
        );
        if (freePlans.length > 0) {
          return res.status(400).json({
            success: false,
            message: 'Only one free plan is allowed'
          });
        }
      }

      // Build update query
      const updateFields = [];
      const values = [];

      const allowedFields = [
        'name', 'description', 'price', 'currency', 'billing_period',
        'max_stores', 'max_users', 'max_departments', 'max_contacts', 'max_devices', 'max_whatsapp_instances',
        'max_whatsapp_cloud_accounts',
        'max_conversations', 'max_messages_per_month', 'max_faqs', 'max_contact_groups',
        'whatsapp_enabled', 'ai_enabled', 'woocommerce_enabled', 'analytics_enabled',
        'priority_support_enabled', 'api_access_enabled', 'custom_branding_enabled',
        'invoices_enabled', 'max_invoices_per_month',
        'quotes_enabled', 'max_quotes_per_month',
        'widgets_enabled', 'max_widgets',
        'payment_links_enabled', 'max_payment_links_per_month',
        'max_email_accounts', 'max_emails_per_month', 'max_omnichannel_accounts',
        'biolink_enabled', 'max_bio_pages', 'max_short_links', 'max_file_transfers',
        'max_vcards', 'max_event_links', 'max_html_pages', 'max_qr_codes',
        'pix_enabled', 'cash_enabled',
        'is_trial', 'trial_days', 'is_free',
        'stripe_price_id', 'paypal_plan_id', 'sort_order', 'active'
      ];

      for (const field of allowedFields) {
        if (updates[field] !== undefined) {
          updateFields.push(`${field} = ?`);
          values.push(updates[field]);
        }
      }

      if (updateFields.length === 0) {
        return res.status(400).json({
          success: false,
          message: 'No fields to update'
        });
      }

      values.push(id);

      await pool.execute(
        `UPDATE subscription_plans SET ${updateFields.join(', ')} WHERE id = ?`,
        values
      );

      logger.info('Plan updated', { planId: id });

      return res.json({
        success: true,
        message: 'Plan updated successfully'
      });
    } catch (error) {
      logger.error('Error updating plan', { error: error.message });
      return res.status(500).json({
        success: false,
        message: 'Error updating plan'
      });
    }
  }

  /**
   * Delete subscription plan
   * DELETE /api/superadmin/plans/:id
   */
  static async deletePlan(req, res) {
    try {
      const { id } = req.params;

      // Check if plan has active subscriptions
      const [tenants] = await pool.execute(
        'SELECT COUNT(*) as count FROM tenants WHERE plan_id = ? AND status = ?',
        [id, 'active']
      );

      if (tenants[0].count > 0) {
        return res.status(400).json({
          success: false,
          message: 'Cannot delete plan with active subscriptions'
        });
      }

      await pool.execute('DELETE FROM subscription_plans WHERE id = ?', [id]);

      logger.info('Plan deleted', { planId: id });

      return res.json({
        success: true,
        message: 'Plan deleted successfully'
      });
    } catch (error) {
      logger.error('Error deleting plan', { error: error.message });
      return res.status(500).json({
        success: false,
        message: 'Error deleting plan'
      });
    }
  }

  /**
   * Toggle plan status
   * PUT /api/superadmin/plans/:id/toggle-status
   */
  static async togglePlanStatus(req, res) {
    try {
      const { id } = req.params;

      const [plan] = await pool.execute(
        'SELECT active FROM subscription_plans WHERE id = ?',
        [id]
      );

      if (plan.length === 0) {
        return res.status(404).json({
          success: false,
          message: 'Plan not found'
        });
      }

      const newStatus = !plan[0].active;

      await pool.execute(
        'UPDATE subscription_plans SET active = ? WHERE id = ?',
        [newStatus, id]
      );

      logger.info('Plan status toggled', { planId: id, newStatus });

      return res.json({
        success: true,
        message: `Plan ${newStatus ? 'activated' : 'deactivated'} successfully`,
        data: { active: newStatus }
      });
    } catch (error) {
      logger.error('Error toggling plan status', { error: error.message });
      return res.status(500).json({
        success: false,
        message: 'Error updating plan status'
      });
    }
  }
}

module.exports = SuperAdminPlanController;
