import { Router, Request, Response } from 'express';
import { db } from '../database/connection';
import { pantrySettings } from '../database/schema';
import { eq } from 'drizzle-orm';
import { authenticateUser, requireAdmin } from '../middleware/auth';

const router = Router();

// Single-row table: first GET seeds defaults if the row doesn't exist yet.
router.get('/', authenticateUser, async (req: Request, res: Response) => {
  try {
    const [settings] = await db
      .select()
      .from(pantrySettings)
      .limit(1);

    // If no settings exist, create default settings
    if (!settings) {
      const [newSettings] = await db
        .insert(pantrySettings)
        .values({
          pantryName: 'Community Food Pantry',
          contactPhone: '',
          address: '',
          lowStockThreshold: 5,
          expiryWarningDays: 7,
        })
        .returning();
      
      return res.json({ settings: newSettings });
    }

    return res.json({ settings });
  } catch (error) {
    console.error('Error fetching settings:', error);
    return res.status(500).json({ error: 'Failed to fetch settings' });
  }
});

// PUT /api/settings - Update pantry settings (admin only)
router.put('/', authenticateUser, requireAdmin, async (req: Request, res: Response) => {
  try {
    const { pantryName, contactPhone, address, lowStockThreshold, expiryWarningDays } = req.body;

    // Get existing settings
    const [existing] = await db
      .select()
      .from(pantrySettings)
      .limit(1);

    let updatedSettings;

    if (existing) {
      // Update existing settings
      [updatedSettings] = await db
        .update(pantrySettings)
        .set({
          pantryName,
          contactPhone,
          address,
          lowStockThreshold,
          expiryWarningDays,
          updatedAt: new Date(),
        })
        .where(eq(pantrySettings.id, existing.id))
        .returning();
    } else {
      // Create new settings if none exist
      [updatedSettings] = await db
        .insert(pantrySettings)
        .values({
          pantryName,
          contactPhone,
          address,
          lowStockThreshold,
          expiryWarningDays,
        })
        .returning();
    }

    return res.json({ settings: updatedSettings });
  } catch (error) {
    console.error('Error updating settings:', error);
    return res.status(500).json({ error: 'Failed to update settings' });
  }
});

export { router as settingsRoutes };

