import { createClient } from '@supabase/supabase-js';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { email, password, username } = body;

    // Validate input
    if (!email || !password || !username) {
      return NextResponse.json(
        { error: 'Email, password, dan username harus diisi' },
        { status: 400 }
      );
    }

    // Validate env variables
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
    const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

    if (!supabaseUrl || !supabaseAnonKey) {
      console.error('Missing Supabase credentials');
      return NextResponse.json(
        { error: 'Server configuration error' },
        { status: 500 }
      );
    }

    // Create client with anon key (not service role)
    const supabase = createClient(supabaseUrl, supabaseAnonKey);

    // Check if username already exists
    try {
      const { data: existingUser } = await supabase
        .from('profiles')
        .select('id')
        .eq('username', username)
        .single();

      if (existingUser) {
        return NextResponse.json(
          { error: 'Username sudah digunakan' },
          { status: 400 }
        );
      }
    } catch (e) {
      // No user found is ok (expected)
    }

    // Sign up with Supabase Auth
    const { data: authData, error: authError } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: {
          username: username,
        },
        // For development, don't require email confirmation
        emailRedirectTo: undefined,
      },
    });

    if (authError) {
      console.error('Auth error:', authError);
      return NextResponse.json(
        { error: authError.message },
        { status: 400 }
      );
    }

    if (!authData.user) {
      return NextResponse.json(
        { error: 'Signup failed' },
        { status: 400 }
      );
    }

    // Wait for trigger to create profile
    await new Promise(resolve => setTimeout(resolve, 1000));

    // Update username if not set by trigger
    try {
      await supabase
        .from('profiles')
        .update({ username })
        .eq('id', authData.user.id);
    } catch (e) {
      console.error('Error updating profile:', e);
    }

    return NextResponse.json(
      { 
        message: 'Pendaftaran berhasil. Silakan verifikasi email Anda.',
        user: authData.user 
      },
      { status: 201 }
    );
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error('Signup error:', errorMessage);
    return NextResponse.json(
      { error: `Server error: ${errorMessage}` },
      { status: 500 }
    );
  }
}
