import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import { createAdminClient } from '@/lib/supabase/admin';
import { validatePhpassPassword } from '@/lib/auth/phpass';

export async function POST(request: NextRequest) {
  try {
    const { email, password } = await request.json();

    if (!email || !password) {
      return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
    }

    const supabase = await createClient();

    // 1. Look up the legacy WordPress user by email
    const { data: wpUser, error: lookupError } = await supabase
      .rpc('get_wp_user_hash', { p_email: email.toLowerCase().trim() });

    // No legacy WP record → fall through to native Supabase auth.
    // Covers users created directly via the Auth Admin API (e.g. modern
    // staff accounts that never lived in the WP install).
    if (lookupError || !wpUser || wpUser.length === 0) {
      const { data: nativeSignIn, error: nativeErr } = await supabase.auth.signInWithPassword({
        email: email.toLowerCase().trim(),
        password,
      });
      if (nativeErr || !nativeSignIn.session) {
        return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
      }
      return NextResponse.json({
        success: true,
        session: nativeSignIn.session,
        user: nativeSignIn.user,
        migrated: true,
        legacy: false,
      });
    }

    const legacyUser = wpUser[0];

    // 2. Check if account is active
    if (!legacyUser.is_active) {
      return NextResponse.json(
        { error: 'This account has been disabled. Please contact support.' },
        { status: 403 }
      );
    }

    // 3. If the legacy row is already linked to an auth user (password upgraded
    //    via a previous successful login, or relinked manually), skip phpass
    //    entirely — the legacy hash is stale once a Supabase password exists.
    if (legacyUser.auth_user_id || legacyUser.password_upgraded) {
      const { data: signInData, error: signInError } = await supabase.auth.signInWithPassword({
        email: email.toLowerCase().trim(),
        password,
      });
      if (signInError || !signInData.session) {
        return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
      }
      return NextResponse.json({
        success: true,
        session: signInData.session,
        user: signInData.user,
        migrated: true,
        legacy: true,
      });
    }

    // 4. First-time login for a never-migrated WP user — validate phpass.
    const passwordValid = await validatePhpassPassword(password, legacyUser.wp_hashed_password);
    if (!passwordValid) {
      return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
    }

    // (legacy fallthrough — auth_user_id is null at this point, but keep the
    // shape of the prior post-validation branch for code readability.)
    if (legacyUser.auth_user_id) {
      // User already migrated — sign in normally
      const { data: signInData, error: signInError } = await supabase.auth.signInWithPassword({
        email: email.toLowerCase().trim(),
        password,
      });

      if (!signInError && signInData.session) {
        return NextResponse.json({
          success: true,
          session: signInData.session,
          user: signInData.user,
          migrated: true,
        });
      }
    }

    // 5. Create a new Supabase auth account for this legacy user (transparent migration).
    //    admin.createUser requires the service_role key — use the admin client.
    const admin = createAdminClient();
    const { data: signUpData, error: signUpError } = await admin.auth.admin.createUser({
      email: email.toLowerCase().trim(),
      password,
      email_confirm: true,
      user_metadata: {
        full_name: legacyUser.display_name || legacyUser.wp_username,
        role: legacyUser.role,
        wp_user_id: legacyUser.wp_id,
        wp_username: legacyUser.wp_username,
      },
    });

    if (signUpError) {
      console.error('Failed to create Supabase user for legacy account:', signUpError);
      return NextResponse.json({ error: 'Authentication failed' }, { status: 500 });
    }

    const newAuthUserId = signUpData.user?.id;
    if (!newAuthUserId) {
      return NextResponse.json({ error: 'Authentication failed' }, { status: 500 });
    }

    // 6. Create/update user_profile with legacy data
    await supabase.from('user_profiles').upsert({
      id: newAuthUserId,
      email: email.toLowerCase().trim(),
      full_name: legacyUser.display_name || legacyUser.wp_username,
      role: legacyUser.role,
      wp_user_id: legacyUser.wp_id,
      wp_username: legacyUser.wp_username,
      wp_hashed_password: legacyUser.wp_hashed_password,
      password_upgraded: true,
      is_active: true,
    }, { onConflict: 'id' });

    // 7. Mark password as upgraded in legacy table
    await supabase.rpc('mark_wp_password_upgraded', {
      p_wp_id: legacyUser.wp_id,
      p_auth_user_id: newAuthUserId,
    });

    // 8. Sign in the newly created user
    const { data: finalSignIn, error: finalSignInError } = await supabase.auth.signInWithPassword({
      email: email.toLowerCase().trim(),
      password,
    });

    if (finalSignInError || !finalSignIn.session) {
      return NextResponse.json({ error: 'Authentication failed after migration' }, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      session: finalSignIn.session,
      user: finalSignIn.user,
      migrated: false,
      firstLogin: true,
    });
  } catch (error) {
    console.error('WP login error:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
