import { NextRequest, NextResponse } from 'next/server';
import { createServerClient } from '@/shared/db/supabase-client';
import { registerInputSchema } from './schemas';
import type { RegisterOutput } from './schemas';

// --- ASA GENERATED START ---
// Route handler for auth/register slice.
// Uses Supabase Auth signUp — profile created automatically via handle_new_user() trigger.
// Security: server-side validation, no client trust.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export async function POST(request: NextRequest): Promise<NextResponse<RegisterOutput>> {
  try {
    const body = await request.json();
    const parsed = registerInputSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.errors[0]?.message ?? 'Invalid input' },
        { status: 400 },
      );
    }

    const { email, password, display_name } = parsed.data;
    const supabase = createServerClient();

    const { data, error } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: { display_name },
      },
    });

    if (error) {
      return NextResponse.json(
        { success: false, error: error.message },
        { status: 400 },
      );
    }

    // Check if user already exists (Supabase returns user with identities: [] for duplicates)
    if (data.user && data.user.identities?.length === 0) {
      return NextResponse.json(
        { success: false, error: 'An account with this email already exists' },
        { status: 409 },
      );
    }

    return NextResponse.json({ success: true, error: null }, { status: 201 });
  } catch {
    return NextResponse.json(
      { success: false, error: 'Registration failed. Please try again.' },
      { status: 500 },
    );
  }
}

// --- USER CODE END ---
