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

export const dynamic = 'force-dynamic';

/**
 * GET /api/saas-admin/features
 * Returns all feature definitions configured in the system.
 */
export async function GET(req: NextRequest) {
  try {
    const features = await db.getFeatureDefinitions();
    return NextResponse.json({
      success: true,
      features,
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to fetch features' },
      { status: 500 }
    );
  }
}

/**
 * PUT /api/saas-admin/features
 * Admin updates feature label, description, plan availability, limits/quotas, or order.
 */
export async function PUT(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 { id } = body;
    if (!id) {
      return NextResponse.json({ success: false, error: 'Feature id is required' }, { status: 400 });
    }

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

    const updates: Partial<FeatureDefinition> = {};
    if (body.name !== undefined) updates.name = String(body.name).trim();
    if (body.description !== undefined) updates.description = body.description ? String(body.description).trim() : null;
    if (body.category !== undefined) updates.category = String(body.category).trim();
    if (body.display_order !== undefined) updates.display_order = parseInt(body.display_order, 10) || 0;
    if (body.is_visible !== undefined) updates.is_visible = Boolean(body.is_visible);
    if (body.basic_value !== undefined) updates.basic_value = String(body.basic_value).trim();
    if (body.growth_value !== undefined) updates.growth_value = String(body.growth_value).trim();
    if (body.scale_value !== undefined) updates.scale_value = String(body.scale_value).trim();
    if (body.basic_enabled !== undefined) updates.basic_enabled = Boolean(body.basic_enabled);
    if (body.growth_enabled !== undefined) updates.growth_enabled = Boolean(body.growth_enabled);
    if (body.scale_enabled !== undefined) updates.scale_enabled = Boolean(body.scale_enabled);
    if (body.basic_limit !== undefined) {
      updates.basic_limit = body.basic_limit === null || body.basic_limit === '' ? null : parseInt(body.basic_limit, 10);
    }
    if (body.growth_limit !== undefined) {
      updates.growth_limit = body.growth_limit === null || body.growth_limit === '' ? null : parseInt(body.growth_limit, 10);
    }
    if (body.scale_limit !== undefined) {
      updates.scale_limit = body.scale_limit === null || body.scale_limit === '' ? null : parseInt(body.scale_limit, 10);
    }

    const updated = await db.updateFeatureDefinition(id, updates);

    // Audit log
    try {
      const adminName = session.user?.name || 'Super Admin';
      await db.createStoreActivityLog({
        shop_id: 'saas_admin',
        shopify_domain: 'system.global',
        action: 'feature_definition_updated',
        actor: adminName,
        description: `Updated feature definition "${id}" (${updated?.name})`,
        metadata: { id, updates },
      });
    } catch {}

    return NextResponse.json({
      success: true,
      message: `Feature '${updated?.name || id}' updated successfully. Changes are live on frontend.`,
      feature: updated,
    });
  } catch (err: any) {
    return NextResponse.json(
      { success: false, error: err?.message || 'Failed to update feature definition' },
      { status: 500 }
    );
  }
}

/**
 * POST /api/saas-admin/features
 * Admin creates a new custom feature definition.
 */
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 { id, name } = body;
    if (!id || !name) {
      return NextResponse.json({ success: false, error: 'id and name are required' }, { status: 400 });
    }

    const cleanId = String(id).trim().toLowerCase();
    const newFeature: FeatureDefinition = {
      id: cleanId,
      name: String(name).trim(),
      description: body.description ? String(body.description).trim() : null,
      display_order: parseInt(body.display_order, 10) || 99,
      is_visible: body.is_visible !== undefined ? Boolean(body.is_visible) : true,
      category: body.category ? String(body.category).trim() : 'General',
      basic_value: body.basic_value ? String(body.basic_value).trim() : 'No',
      growth_value: body.growth_value ? String(body.growth_value).trim() : 'Yes',
      scale_value: body.scale_value ? String(body.scale_value).trim() : 'Yes',
      basic_enabled: Boolean(body.basic_enabled),
      growth_enabled: Boolean(body.growth_enabled),
      scale_enabled: Boolean(body.scale_enabled),
      basic_limit: body.basic_limit === null || body.basic_limit === '' ? null : parseInt(body.basic_limit, 10),
      growth_limit: body.growth_limit === null || body.growth_limit === '' ? null : parseInt(body.growth_limit, 10),
      scale_limit: body.scale_limit === null || body.scale_limit === '' ? null : parseInt(body.scale_limit, 10),
    };

    const created = await db.updateFeatureDefinition(cleanId, newFeature);

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