import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Settings } from '@/models/Settings';
import { getAuthUser, requireAdmin } from '@/lib/auth';
import { encryptSecret, maskSecret, decryptSecret } from '@/lib/security';

// GET /api/settings - Retrieve settings
// Public: returns active public-facing settings based on current mode
// Admin: returns complete settings with secret keys safely masked (e.g. sk_test_••••••••)
export async function GET(req: NextRequest) {
  try {
    await dbConnect();
    const user = getAuthUser(req);
    const isAdmin = user && (user.role === 'admin' || user.role === 'super_admin');
    const settings = await Settings.getSettings();

    const stripeMode = settings.stripe?.mode || 'test';
    const paypalMode = settings.paypal?.mode || 'test';

    // If public visitor or student, return active keys according to selected mode
    if (!isAdmin) {
      const activeStripePub = stripeMode === 'live'
        ? (settings.stripe?.livePublishableKey || settings.stripe?.publishableKey || '')
        : (settings.stripe?.testPublishableKey || settings.stripe?.publishableKey || '');

      const activePaypalClient = paypalMode === 'live'
        ? (settings.paypal?.liveClientId || settings.paypal?.clientId || '')
        : (settings.paypal?.testClientId || settings.paypal?.clientId || '');

      return NextResponse.json({
        success: true,
        settings: {
          stripe: {
            mode: stripeMode,
            publishableKey: activeStripePub,
            isEnabled: settings.stripe?.isEnabled ?? true,
          },
          paypal: {
            mode: paypalMode,
            clientId: activePaypalClient,
            isEnabled: settings.paypal?.isEnabled ?? true,
          },
          bankTransfer: {
            bankName: settings.bankTransfer?.bankName || '',
            accountHolder: settings.bankTransfer?.accountHolder || '',
            iban: settings.bankTransfer?.iban || '',
            bicSwift: settings.bankTransfer?.bicSwift || '',
            paymentInstructions: settings.bankTransfer?.paymentInstructions || '',
            // paymentScreenshot: settings.bankTransfer?.paymentScreenshot || settings.bankTransfer?.paymentScreenShot || '',
            paymentScreenShot: settings.bankTransfer?.paymentScreenShot || '',
            isEnabled: settings.bankTransfer?.isEnabled ?? true,
          },
          defaultCourseExpiryMonths: settings.defaultCourseExpiryMonths || 4,
          legalPages: {
            privacyPolicy: settings.legalPages?.privacyPolicy || '',
            termsAndConditions: settings.legalPages?.termsAndConditions || '',
          },
        },
      });
    }

    // Admin view: return settings with full secrets so admin can view/copy/edit
    const adminSettings = {
      _id: settings._id,
      stripe: {
        mode: stripeMode,
        isEnabled: settings.stripe?.isEnabled ?? true,
        testPublishableKey: settings.stripe?.testPublishableKey || settings.stripe?.publishableKey || '',
        testSecretKey: settings.stripe?.testSecretKeyEncrypted
          ? decryptSecret(settings.stripe.testSecretKeyEncrypted)
          : (settings.stripe?.secretKeyEncrypted ? decryptSecret(settings.stripe.secretKeyEncrypted) : ''),
        livePublishableKey: settings.stripe?.livePublishableKey || '',
        liveSecretKey: settings.stripe?.liveSecretKeyEncrypted ? decryptSecret(settings.stripe.liveSecretKeyEncrypted) : '',
      },
      paypal: {
        mode: paypalMode,
        isEnabled: settings.paypal?.isEnabled ?? true,
        testClientId: settings.paypal?.testClientId || settings.paypal?.clientId || '',
        testClientSecret: settings.paypal?.testClientSecretEncrypted
          ? decryptSecret(settings.paypal.testClientSecretEncrypted)
          : (settings.paypal?.clientSecretEncrypted ? decryptSecret(settings.paypal.clientSecretEncrypted) : ''),
        liveClientId: settings.paypal?.liveClientId || '',
        liveClientSecret: settings.paypal?.liveClientSecretEncrypted ? decryptSecret(settings.paypal.liveClientSecretEncrypted) : '',
      },
      bankTransfer: settings.bankTransfer,
      defaultCourseExpiryMonths: settings.defaultCourseExpiryMonths || 4,
      legalPages: settings.legalPages,
      updatedAt: settings.updatedAt,
      lastUpdatedBy: settings.lastUpdatedBy,
    };

    return NextResponse.json({
      success: true,
      settings: adminSettings,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error fetching settings' },
      { status: 500 }
    );
  }
}

// PUT /api/settings - Admin updates settings (sensitive keys encrypted via AES-256-GCM)
export async function PUT(req: NextRequest) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();
    const settings = await Settings.getSettings();

    // Update Stripe
    if (body.stripe) {
      if (body.stripe.mode && ['test', 'live'].includes(body.stripe.mode)) {
        settings.stripe.mode = body.stripe.mode;
      }
      if (typeof body.stripe.isEnabled === 'boolean') {
        settings.stripe.isEnabled = body.stripe.isEnabled;
      }

      // Test keys
      if (body.stripe.testPublishableKey !== undefined) {
        settings.stripe.testPublishableKey = body.stripe.testPublishableKey;
      }
      if (body.stripe.testSecretKey && !body.stripe.testSecretKey.includes('••••')) {
        settings.stripe.testSecretKeyEncrypted = encryptSecret(body.stripe.testSecretKey);
      }

      // Live keys
      if (body.stripe.livePublishableKey !== undefined) {
        settings.stripe.livePublishableKey = body.stripe.livePublishableKey;
      }
      if (body.stripe.liveSecretKey && !body.stripe.liveSecretKey.includes('••••')) {
        settings.stripe.liveSecretKeyEncrypted = encryptSecret(body.stripe.liveSecretKey);
      }

      // Fallback update for active mode
      if (settings.stripe.mode === 'live') {
        settings.stripe.publishableKey = settings.stripe.livePublishableKey;
        if (settings.stripe.liveSecretKeyEncrypted) settings.stripe.secretKeyEncrypted = settings.stripe.liveSecretKeyEncrypted;
      } else {
        settings.stripe.publishableKey = settings.stripe.testPublishableKey;
        if (settings.stripe.testSecretKeyEncrypted) settings.stripe.secretKeyEncrypted = settings.stripe.testSecretKeyEncrypted;
      }
    }

    // Update PayPal
    if (body.paypal) {
      const mode = body.paypal.mode === 'sandbox' ? 'test' : body.paypal.mode;
      if (mode && ['test', 'live'].includes(mode)) {
        settings.paypal.mode = mode;
      }
      if (typeof body.paypal.isEnabled === 'boolean') {
        settings.paypal.isEnabled = body.paypal.isEnabled;
      }

      // Test credentials
      if (body.paypal.testClientId !== undefined) {
        settings.paypal.testClientId = body.paypal.testClientId;
      }
      if (body.paypal.testClientSecret && !body.paypal.testClientSecret.includes('••••')) {
        settings.paypal.testClientSecretEncrypted = encryptSecret(body.paypal.testClientSecret);
      }

      // Live credentials
      if (body.paypal.liveClientId !== undefined) {
        settings.paypal.liveClientId = body.paypal.liveClientId;
      }
      if (body.paypal.liveClientSecret && !body.paypal.liveClientSecret.includes('••••')) {
        settings.paypal.liveClientSecretEncrypted = encryptSecret(body.paypal.liveClientSecret);
      }

      // Fallback update for active mode
      if (settings.paypal.mode === 'live') {
        settings.paypal.clientId = settings.paypal.liveClientId;
        if (settings.paypal.liveClientSecretEncrypted) settings.paypal.clientSecretEncrypted = settings.paypal.liveClientSecretEncrypted;
      } else {
        settings.paypal.clientId = settings.paypal.testClientId;
        if (settings.paypal.testClientSecretEncrypted) settings.paypal.clientSecretEncrypted = settings.paypal.testClientSecretEncrypted;
      }
    }

    // Update Bank Transfer
    if (body.bankTransfer) {
      if (body.bankTransfer.bankName !== undefined) settings.bankTransfer.bankName = body.bankTransfer.bankName;
      if (body.bankTransfer.accountHolder !== undefined) settings.bankTransfer.accountHolder = body.bankTransfer.accountHolder;
      if (body.bankTransfer.iban !== undefined) settings.bankTransfer.iban = body.bankTransfer.iban;
      if (body.bankTransfer.bicSwift !== undefined) settings.bankTransfer.bicSwift = body.bankTransfer.bicSwift;
      if (body.bankTransfer.paymentInstructions !== undefined) {
        settings.bankTransfer.paymentInstructions = body.bankTransfer.paymentInstructions;
      }
      // if (body.bankTransfer.paymentScreenshot !== undefined) {
      //   settings.bankTransfer.paymentScreenshot = body.bankTransfer.paymentScreenshot;
      // }
      if (body.bankTransfer.paymentScreenShot !== undefined) {
        settings.bankTransfer.paymentScreenShot = body.bankTransfer.paymentScreenShot;
      }
      if (typeof body.bankTransfer.isEnabled === 'boolean') {
        settings.bankTransfer.isEnabled = body.bankTransfer.isEnabled;
      }
    }

    // Update Default Expiry Months
    if (body.defaultCourseExpiryMonths !== undefined) {
      settings.defaultCourseExpiryMonths = Number(body.defaultCourseExpiryMonths);
    }

    // Update Legal Pages
    if (body.legalPages) {
      if (body.legalPages.privacyPolicy !== undefined) {
        settings.legalPages.privacyPolicy = body.legalPages.privacyPolicy;
      }
      if (body.legalPages.termsAndConditions !== undefined) {
        settings.legalPages.termsAndConditions = body.legalPages.termsAndConditions;
      }
    }

    settings.lastUpdatedBy = auth.user.id as any;
    await settings.save();

    return NextResponse.json({
      success: true,
      message: 'System settings updated successfully',
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating settings' },
      { status: 500 }
    );
  }
}
