import { NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';

import { withAuth } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { errorResponse, ValidationError } from '@/lib/errors';

export const GET = withAuth(async (req, ctx) => {
  try {
    const key = req.nextUrl.searchParams.get('key');
    if (!key) throw new ValidationError('key query parameter is required');

    const setting = await db.query.systemSettings.findFirst({
      where: and(eq(systemSettings.key, key), eq(systemSettings.portId, ctx.portId)),
    });

    // `default` applies ONLY when the setting was never written for this
    // port (row absent). An explicit stored `false` always disables. Lets
    // default-ON settings (e.g. pulse_enabled) gate correctly via
    // ?default=true while default-OFF flags keep the old behaviour.
    const def = req.nextUrl.searchParams.get('default') === 'true';
    const enabled = setting ? setting.value === true : def;
    return NextResponse.json({ enabled });
  } catch (error) {
    return errorResponse(error);
  }
});
