import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { getAdminSession } from '@/lib/auth/adminAuth';
import { PricingPlan } from '@/types';

export const dynamic = 'force-dynamic';

/**
 * GET /api/saas-admin/plans
 * Returns all pricing plans and feature definitions currently configured in MySQL.
 */
export async function GET(req: NextRequest) {
  try {
    const [plans, featureDefinitions] = await Promise.all([
      db.getPlans(),
      db.getFeatureDefinitions(),
    ]);

    return NextResponse.json({
      success: true,
      plans,
      featureDefinitions,
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to fetch pricing plans' },
      { status: 500 }
    );
  }
}

/**
 * PUT /api/saas-admin/plans
 * Super Admin modifies subscription plan name, pricing, limits, features, or trial days.
 * Changes reflect dynamically across SaaS Admin and Merchant Frontend (/pricing).
 */
export async function PUT(req: NextRequest) {
  try {
    // 1. Verify admin session (allow localhost or authenticated admin)
    const session = await getAdminSession(req);
    const host = req.headers.get('host') || '';
    const isLocal = host.includes('localhost') || host.includes('127.0.0.1');
    if (!session.authenticated && !isLocal && process.env.NODE_ENV === 'production') {
      return NextResponse.json({ success: false, error: 'Authentication required' }, { status: 401 });
    }

    const body = await req.json();
    const {
      plan_id,
      name,
      description,
      price,
      yearly_price,
      currency,
      interval,
      yearly_discount_label,
      display_order,
      is_visible,
      sku_limit,
      campaigns_limit,
      trial_days,
      features,
      badge,
      is_active,
      support,
      feature_flags,
      feature_limits,
    } = body;

    if (!plan_id) {
      return NextResponse.json({ success: false, error: 'plan_id is required' }, { status: 400 });
    }

    const existing = await db.getPlan(plan_id);
    if (!existing) {
      return NextResponse.json({ success: false, error: `Plan '${plan_id}' not found` }, { status: 404 });
    }

    // Prepare updates
    const updates: Partial<PricingPlan> = {};
    if (name !== undefined) updates.name = String(name).trim();
    if (description !== undefined) updates.description = description ? String(description).trim() : null;
    if (price !== undefined) updates.price = Math.max(0, parseFloat(price) || 0);
    if (yearly_price !== undefined) updates.yearly_price = Math.max(0, parseFloat(yearly_price) || 0);
    if (currency !== undefined) updates.currency = String(currency).trim().toUpperCase();
    if (interval !== undefined) updates.interval = interval === 'year' ? 'year' : 'month';
    if (yearly_discount_label !== undefined) updates.yearly_discount_label = yearly_discount_label ? String(yearly_discount_label).trim() : null;
    if (display_order !== undefined) updates.display_order = parseInt(display_order, 10) || 0;
    if (is_visible !== undefined) updates.is_visible = Boolean(is_visible);
    if (sku_limit !== undefined) updates.sku_limit = sku_limit === null || sku_limit === '' ? null : parseInt(sku_limit, 10);
    if (campaigns_limit !== undefined) updates.campaigns_limit = campaigns_limit === null || campaigns_limit === '' ? null : parseInt(campaigns_limit, 10);
    if (trial_days !== undefined) updates.trial_days = Math.max(0, parseInt(trial_days, 10) || 0);
    if (features !== undefined) {
      updates.features = Array.isArray(features) ? features : String(features).split('\n').map((f) => f.trim()).filter(Boolean);
    }
    if (badge !== undefined) updates.badge = badge ? String(badge).trim() : null;
    if (is_active !== undefined) updates.is_active = Boolean(is_active);
    if (support !== undefined) updates.support = String(support).trim();
    if (feature_flags !== undefined) updates.feature_flags = feature_flags;
    if (feature_limits !== undefined) updates.feature_limits = feature_limits;

    const updatedPlan = await db.updatePlan(plan_id, updates);

    // Record audit / activity log
    try {
      const adminName = session.user?.name || 'Super Admin';
      await db.createStoreActivityLog({
        shop_id: 'saas_admin',
        shopify_domain: 'system.global',
        action: 'pricing_plan_updated',
        actor: adminName,
        description: `Updated plan "${plan_id}": Name="${updatedPlan?.name}", Price=$${updatedPlan?.price}/mo, Trial=${updatedPlan?.trial_days}d`,
        metadata: {
          plan_id,
          updates,
        },
      });
    } catch {}

    return NextResponse.json({
      success: true,
      message: `Plan '${updatedPlan?.name || plan_id}' updated successfully. Changes are live globally.`,
      plan: updatedPlan,
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to update plan' },
      { status: 500 }
    );
  }
}

/**
 * POST /api/saas-admin/plans
 * Super Admin creates a new plan.
 */
export async function POST(req: NextRequest) {
  try {
    const session = await getAdminSession(req);
    const host = req.headers.get('host') || '';
    const isLocal = host.includes('localhost') || host.includes('127.0.0.1');
    if (!session.authenticated && !isLocal && process.env.NODE_ENV === 'production') {
      return NextResponse.json({ success: false, error: 'Authentication required' }, { status: 401 });
    }

    const body = await req.json();
    const { plan_id, name, price } = body;
    if (!plan_id || !name) {
      return NextResponse.json({ success: false, error: 'plan_id and name are required' }, { status: 400 });
    }

    const cleanId = String(plan_id).trim().toLowerCase().replace(/[^a-z0-9_-]/g, '_');
    const existing = await db.getPlan(cleanId);
    if (existing) {
      return NextResponse.json({ success: false, error: `Plan with ID '${cleanId}' already exists.` }, { status: 409 });
    }

    const newPlan: PricingPlan = {
      id: cleanId,
      name: String(name).trim(),
      description: body.description ? String(body.description).trim() : null,
      price: Math.max(0, parseFloat(price) || 0),
      yearly_price: body.yearly_price != null ? Math.max(0, parseFloat(body.yearly_price) || 0) : Math.max(0, parseFloat(price) || 0) * 12 * 0.8,
      currency: body.currency ? String(body.currency).trim().toUpperCase() : 'USD',
      interval: body.interval === 'year' ? 'year' : 'month',
      yearly_discount_label: body.yearly_discount_label ? String(body.yearly_discount_label).trim() : 'Save 20%',
      display_order: parseInt(body.display_order, 10) || 10,
      is_visible: body.is_visible !== undefined ? Boolean(body.is_visible) : true,
      sku_limit: body.sku_limit === null || body.sku_limit === '' ? null : parseInt(body.sku_limit, 10),
      campaigns_limit: body.campaigns_limit === null || body.campaigns_limit === '' ? null : parseInt(body.campaigns_limit, 10),
      trial_days: Math.max(0, parseInt(body.trial_days, 10) || 0),
      capi_enabled: Boolean(body.capi_enabled),
      supplementary_feeds: Boolean(body.supplementary_feeds),
      custom_titles: Boolean(body.custom_titles),
      website_audit: Boolean(body.website_audit),
      dedicated_manager: Boolean(body.dedicated_manager),
      support: body.support ? String(body.support).trim() : 'Chat/Email Support',
      features: Array.isArray(body.features) ? body.features : String(body.features || '').split('\n').map((f) => f.trim()).filter(Boolean),
      badge: body.badge ? String(body.badge).trim() : null,
      is_active: body.is_active !== undefined ? Boolean(body.is_active) : true,
    };

    const created = await db.updatePlan(cleanId, newPlan);

    return NextResponse.json({
      success: true,
      message: `Plan '${created?.name}' created successfully.`,
      plan: created,
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to create plan' },
      { status: 500 }
    );
  }
}
