// API route for getting and updating SMTP settings (protected by admin check)
import { NextResponse } from 'next/server';
import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';
export async function GET() {
    const cookieStore = await cookies();

  const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || '';
  const supabase = createServerClient(
    supabaseUrl,
    process.env.SUPABASE_SERVICE_ROLE_KEY ?? '',
    {
      cookies: {
        getAll() {
          return cookieStore.getAll()
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            )
          } catch {
            // Kann in einer API-Route ignoriert werden, wenn nur gelesen wird
          }
        },
      },
      cookieOptions: {
        name: "webshop-auth-token",
      },
    }
  );

  const { data: { user: authUser }, error: authError } = await supabase.auth.getUser();
  if (authError || !authUser) {
    return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
  }
  const { data: user } = await supabase.from('users').select('role').eq('id', authUser.id).single();
  if (!user || user.role !== 'admin') {
    return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
  }

  const { data, error } = await supabase.from('settings').select('*').maybeSingle();
  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
  return NextResponse.json({ 
    settings: data || { host: '', port: 587, secure: false, user: '', pass: '' } 
  });
}

export async function POST(request: Request) {
    const cookieStore = await cookies();

    const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL || '';
    const supabase = createServerClient(
      supabaseUrl,
      process.env.SUPABASE_SERVICE_ROLE_KEY ?? '',
      {
        cookies: {
          getAll() {
            return cookieStore.getAll()
          },
          setAll(cookiesToSet) {
            try {
              cookiesToSet.forEach(({ name, value, options }) =>
                cookieStore.set(name, value, options)
              )
            } catch {
              // Kann in einer API-Route ignoriert werden, wenn nur gelesen wird
            }
          },
        },
        cookieOptions: {
          name: "webshop-auth-token",
        },
      }
    );

  const { data: { user: authUser }, error: authError } = await supabase.auth.getUser();
  if (authError || !authUser) {
    return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
  }
  const { data: user } = await supabase.from('users').select('role').eq('id', authUser.id).single();
  if (!user || user.role !== 'admin') {
    return NextResponse.json({ error: 'Insufficient permissions' }, { status: 403 });
  }

  const payload = await request.json(); // expect {host, port, secure, user, pass}
  const { error } = await supabase
    .from('settings')
    .upsert({ id: 'smtp', ...payload });
  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
  return NextResponse.json({ message: 'SMTP settings saved' });
}
