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

export const dynamic = 'force-dynamic';

/**
 * PUT /api/plans/admin
 * Admin modifies plan pricing, SKU limits, features, or custom properties.
 */
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { plan_id, updates } = body;

    if (!plan_id || !updates) {
      return NextResponse.json(
        { success: false, error: 'plan_id and updates object are required' },
        { status: 400 }
      );
    }

    const updated = await db.updatePlan(plan_id, updates as Partial<PricingPlan>);

    // Also record audit log for modern apparel demo or admin
    await db.recordAuditLog({
      id: `audit_plan_admin_${Date.now()}`,
      shop_id: 'shop_demo_123',
      action: `Admin updated plan ${plan_id}: price=$${updates.price ?? 'unchanged'}, sku_limit=${updates.sku_limit ?? 'unchanged'}`,
      actor: 'merchant',
      metadata: updates,
      created_at: new Date().toISOString(),
    });

    logger.info(`Admin updated plan ${plan_id}`, updates);

    return NextResponse.json({
      success: true,
      message: `Plan ${plan_id} updated successfully`,
      plan: updated,
    });
  } catch (error) {
    logger.error('Failed to update plan via admin', { error: String(error) });
    return NextResponse.json(
      { success: false, error: 'Failed to update plan: ' + String(error) },
      { status: 500 }
    );
  }
}

/**
 * POST /api/plans/admin
 * Admin actions: reset plans to default, or set custom store SKU limits.
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, shop_id, custom_sku_limit } = body;

    if (action === 'reset_defaults') {
      const resetPlans = await db.resetDefaultPlans();
      return NextResponse.json({
        success: true,
        message: 'Plans reset to standard factory defaults',
        plans: resetPlans,
      });
    }

    if (action === 'set_store_custom_limit' || action === 'set_store_plan' || action === 'update_store') {
      const { shop_id, shop_domain, plan, custom_sku_limit, trial_days, subscription_status } = body;
      let shop = shop_id ? await db.getShop(shop_id) : null;
      if (!shop && shop_domain) {
        shop = await db.getShopByDomain(shop_domain);
      }
      if (!shop) {
        return NextResponse.json({ success: false, error: 'Shop not found' }, { status: 404 });
      }

      await db.setShopPlan(shop.id, plan || shop.plan, {
        plan_custom_sku_limit: custom_sku_limit !== undefined ? custom_sku_limit : shop.plan_custom_sku_limit,
        trial_days: trial_days !== undefined ? trial_days : shop.trial_days,
        subscription_status: subscription_status || shop.subscription_status,
      });

      return NextResponse.json({
        success: true,
        message: `Plan settings updated for ${shop.shopify_domain}`,
      });
    }

    return NextResponse.json({ success: false, error: 'Invalid admin action' }, { status: 400 });
  } catch (error) {
    return NextResponse.json(
      { success: false, error: 'Admin action failed: ' + String(error) },
      { status: 500 }
    );
  }
}
