import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { getReminderSettingsD1, upsertReminderSettingsD1 } from '@/lib/d1';

export async function GET() {
  try {
    const session = await getSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const settings = await getReminderSettingsD1(session.user.id);

    if (!settings) {
      return NextResponse.json({
        enabled: false,
        reminderTime: '09:00',
        frequency: 'daily',
      });
    }

    return NextResponse.json({
      enabled: !!settings.enabled,
      reminderTime: settings.reminderTime,
      frequency: settings.frequency || 'daily',
      hourlyStart: settings.hourlyStart || '09:00',
      hourlyEnd: settings.hourlyEnd || '21:00',
      timezone: settings.timezone || 'UTC',
    });
  } catch (error) {
    console.error('Error fetching reminder settings:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const session = await getSession();
    if (!session?.user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json() as {
      enabled?: boolean;
      reminderTime?: string;
      frequency?: string;
      hourlyStart?: string;
      hourlyEnd?: string;
      timezone?: string;
    };
    const { enabled, reminderTime, frequency, hourlyStart, hourlyEnd, timezone } = body;

    const settings = await upsertReminderSettingsD1(
      session.user.id,
      enabled ?? false,
      reminderTime ?? '09:00',
      frequency ?? 'daily',
      hourlyStart ?? '09:00',
      hourlyEnd ?? '21:00',
      timezone ?? 'UTC'
    );

    if (!settings) {
      return NextResponse.json({ error: 'Failed to save reminder settings' }, { status: 500 });
    }

    return NextResponse.json({
      enabled: !!settings.enabled,
      reminderTime: settings.reminderTime,
      frequency: settings.frequency || 'daily',
      hourlyStart: settings.hourlyStart || '09:00',
      hourlyEnd: settings.hourlyEnd || '21:00',
      timezone: settings.timezone || 'UTC',
    });
  } catch (error) {
    console.error('Error saving reminder settings:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
