import { NextResponse } from 'next/server';
import Redis from 'ioredis';

export const dynamic = 'force-dynamic';

// Use env var or default to the in-cluster Redis service
const redisHost = process.env.REDIS_HOST || 'redis.platform-data.svc.cluster.local';
const redis = new Redis({ host: redisHost, port: 6379, maxRetriesPerRequest: 1 });

const REDIS_KEY = 'whatsapp_config';

export async function GET() {
  try {
    const raw = await redis.get(REDIS_KEY);
    let data = { 'default-group-url': '', 'trip-group-url': '' };
    if (raw) {
      data = JSON.parse(raw);
    }
    return NextResponse.json({ success: true, data });
  } catch (e) {
    console.error("Redis error:", e.message);
    return NextResponse.json({ success: false, error: "Failed to connect to Redis: " + e.message }, { status: 500 });
  }
}

export async function PUT(req) {
  try {
    const body = await req.json();
    const { defaultGroupUrl, tripGroupUrl } = body;

    const raw = await redis.get(REDIS_KEY);
    let data = {};
    if (raw) data = JSON.parse(raw);
    
    if (defaultGroupUrl) data['default-group-url'] = defaultGroupUrl;
    if (tripGroupUrl) data['trip-group-url'] = tripGroupUrl;

    await redis.set(REDIS_KEY, JSON.stringify(data));

    return NextResponse.json({ success: true, data });
  } catch (e) {
    console.error("Redis error:", e.message);
    return NextResponse.json({ success: false, error: e.message }, { status: 500 });
  }
}
