import { NextResponse } from 'next/server';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import {
  listProviderKeys,
  saveProviderKey,
  deleteProviderKey,
} from '@server/services/provider-keys.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const restaurantId = req.session.restaurantId;
    if (!restaurantId) {
      return NextResponse.json({ error: 'No restaurant context' }, { status: 400 });
    }
    const keys = await listProviderKeys(restaurantId);
    return NextResponse.json({ keys });
  })
);

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const restaurantId = req.session.restaurantId;
    if (!restaurantId) {
      return NextResponse.json({ error: 'No restaurant context' }, { status: 400 });
    }
    const body = await req.json() as { providerName?: string; apiKey?: string };
    if (!body.providerName || !body.apiKey) {
      return NextResponse.json({ error: 'providerName and apiKey are required' }, { status: 400 });
    }
    const key = await saveProviderKey(restaurantId, body.providerName, body.apiKey);
    return NextResponse.json({ key });
  })
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const restaurantId = req.session.restaurantId;
    if (!restaurantId) {
      return NextResponse.json({ error: 'No restaurant context' }, { status: 400 });
    }
    const url = new URL(req.url);
    const providerName = url.searchParams.get('provider');
    if (!providerName) {
      return NextResponse.json({ error: 'provider query param is required' }, { status: 400 });
    }
    await deleteProviderKey(restaurantId, providerName);
    return NextResponse.json({ success: true });
  })
);
