import { NextRequest, NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { db, settings } from '@/lib/db';
import { verifyAdminToken } from '@/lib/auth/tokens';

// GET /api/settings - Get all settings (public endpoint for reading only)
export async function GET() {
  try {
    const allSettings = await db.select().from(settings);

    const settingsObj = allSettings.reduce((acc, setting) => {
      acc[setting.key] = setting.value;
      return acc;
    }, {} as Record<string, string>);

    if (!settingsObj.siteTitle) settingsObj.siteTitle = 'Wishlist';
    if (!settingsObj.homepageSubtext) settingsObj.homepageSubtext = 'Browse and explore available wishlists';
    if (settingsObj.claimingEnabled === undefined) settingsObj.claimingEnabled = 'true';
    if (settingsObj.showQuantity === undefined) settingsObj.showQuantity = 'true';

    return NextResponse.json({
      success: true,
      settings: {
        siteTitle: settingsObj.siteTitle,
        homepageSubtext: settingsObj.homepageSubtext,
        claimingEnabled: settingsObj.claimingEnabled !== 'false',
        showQuantity: settingsObj.showQuantity !== 'false',
      },
    });
  } catch (error) {
    console.error('Error fetching settings:', error);
    return NextResponse.json(
      { error: 'Failed to fetch settings' },
      { status: 500 }
    );
  }
}

// PUT /api/settings - Update settings (admin only)
export async function PUT(request: NextRequest) {
  try {
    if (!verifyAdminToken(request)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const { siteTitle, homepageSubtext, claimingEnabled, showQuantity } = body;

    if (siteTitle !== undefined) {
      const existing = await db
        .select()
        .from(settings)
        .where(eq(settings.key, 'siteTitle'))
        .limit(1);

      if (existing.length > 0) {
        await db
          .update(settings)
          .set({ value: siteTitle, updatedAt: new Date() })
          .where(eq(settings.key, 'siteTitle'));
      } else {
        await db.insert(settings).values({
          key: 'siteTitle',
          value: siteTitle,
        });
      }
    }

    if (homepageSubtext !== undefined) {
      const existing = await db
        .select()
        .from(settings)
        .where(eq(settings.key, 'homepageSubtext'))
        .limit(1);

      if (existing.length > 0) {
        await db
          .update(settings)
          .set({ value: homepageSubtext, updatedAt: new Date() })
          .where(eq(settings.key, 'homepageSubtext'));
      } else {
        await db.insert(settings).values({
          key: 'homepageSubtext',
          value: homepageSubtext,
        });
      }
    }

    for (const [key, val] of [['claimingEnabled', claimingEnabled], ['showQuantity', showQuantity]] as const) {
      if (val !== undefined) {
        const strVal = val ? 'true' : 'false';
        const existing = await db.select().from(settings).where(eq(settings.key, key)).limit(1);
        if (existing.length > 0) {
          await db.update(settings).set({ value: strVal, updatedAt: new Date() }).where(eq(settings.key, key));
        } else {
          await db.insert(settings).values({ key, value: strVal });
        }
      }
    }

    return NextResponse.json({
      success: true,
      message: 'Settings updated successfully',
    });
  } catch (error) {
    console.error('Error updating settings:', error);
    return NextResponse.json(
      { error: 'Failed to update settings' },
      { status: 500 }
    );
  }
}
