import { NextResponse } from 'next/server';
import { query, execute } from '@/lib/db';
import { getAdminSession, hashPassword } from '@/lib/auth';

// GET /api/admin/admins — list admin profiles with pagination
export async function GET(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const { searchParams } = new URL(request.url);
    const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10));
    const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '10', 10)));
    const offset = (page - 1) * limit;

    // Get total count
    const countRows = await query('SELECT COUNT(*) as total FROM admins') as any[];
    const total = countRows?.[0]?.total || 0;

    // Get paginated admins
    const admins = await query(
      'SELECT id, email, username, role, is_active, created_at FROM admins ORDER BY created_at ASC LIMIT ? OFFSET ?',
      [limit, offset]
    ) as any[];

    return NextResponse.json({
      admins: admins || [],
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (err: any) {
    console.error('[admin/admins] GET error:', err?.message ?? err);
    return NextResponse.json({ error: 'Failed to load admins.' }, { status: 500 });
  }
}

// POST /api/admin/admins — create a new admin profile
export async function POST(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  // Only superadmin or admin can create new admins
  if (session.role !== 'superadmin' && session.role !== 'admin') {
    return NextResponse.json({ error: 'Insufficient permissions.' }, { status: 403 });
  }

  try {
    const body = await request.json();
    const { email, username, password, role } = body;

    if (!email || !password) {
      return NextResponse.json({ error: 'Email and password are required.' }, { status: 400 });
    }

    if (password.length < 6) {
      return NextResponse.json({ error: 'Password must be at least 6 characters.' }, { status: 400 });
    }

    const sanitizedEmail = String(email).trim().toLowerCase();
    const sanitizedUsername = username ? String(username).trim().slice(0, 100) : sanitizedEmail.split('@')[0];
    const sanitizedRole = role === 'superadmin' ? 'superadmin' : role === 'user' ? 'user' : 'admin';

    // Check if email already exists
    const existing = await query('SELECT id FROM admins WHERE email = ?', [sanitizedEmail]) as any[];
    if (existing && existing.length > 0) {
      return NextResponse.json({ error: 'An admin with this email already exists.' }, { status: 409 });
    }

    // Generate ID
    const id = `admin_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
    const passwordHash = await hashPassword(password);

    await execute(
      'INSERT INTO admins (id, email, username, password_hash, otp_email, role, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)',
      [id, sanitizedEmail, sanitizedUsername, passwordHash, sanitizedEmail, sanitizedRole]
    );

    return NextResponse.json({
      success: true,
      admin: { id, email: sanitizedEmail, username: sanitizedUsername, role: sanitizedRole },
    });
  } catch (err: any) {
    console.error('[admin/admins] POST error:', err?.message ?? err);
    return NextResponse.json({ error: 'Failed to create admin.' }, { status: 500 });
  }
}

// PUT /api/admin/admins — update an existing admin profile
export async function PUT(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { id, email, username, role, password } = body;

    if (!id) {
      return NextResponse.json({ error: 'Admin ID is required.' }, { status: 400 });
    }

    // Only superadmin can change roles
    if (role && session.role !== 'superadmin') {
      return NextResponse.json({ error: 'Only superadmin can change roles.' }, { status: 403 });
    }

    const updates: string[] = [];
    const params: any[] = [];

    if (email !== undefined) {
      const sanitizedEmail = String(email).trim().toLowerCase();
      // Check if email already exists (excluding current admin)
      const existing = await query('SELECT id FROM admins WHERE email = ? AND id != ?', [sanitizedEmail, id]) as any[];
      if (existing && existing.length > 0) {
        return NextResponse.json({ error: 'An admin with this email already exists.' }, { status: 409 });
      }
      updates.push('email = ?');
      params.push(sanitizedEmail);
    }

    if (username !== undefined) {
      updates.push('username = ?');
      params.push(String(username).trim().slice(0, 100));
    }

    if (role !== undefined && session.role === 'superadmin') {
      updates.push('role = ?');
      params.push(role === 'superadmin' ? 'superadmin' : role === 'user' ? 'user' : 'admin');
    }

    if (password) {
      if (password.length < 6) {
        return NextResponse.json({ error: 'Password must be at least 6 characters.' }, { status: 400 });
      }
      const passwordHash = await hashPassword(password);
      updates.push('password_hash = ?');
      params.push(passwordHash);
    }

    if (updates.length === 0) {
      return NextResponse.json({ error: 'No fields to update.' }, { status: 400 });
    }

    params.push(id);
    await execute(
      `UPDATE admins SET ${updates.join(', ')} WHERE id = ?`,
      params
    );

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error('[admin/admins] PUT error:', err?.message ?? err);
    return NextResponse.json({ error: 'Failed to update admin.' }, { status: 500 });
  }
}

// DELETE /api/admin/admins — delete an admin profile
export async function DELETE(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  // Only superadmin or admin can delete
  if (session.role !== 'superadmin' && session.role !== 'admin') {
    return NextResponse.json({ error: 'Insufficient permissions.' }, { status: 403 });
  }

  try {
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');

    if (!id) {
      return NextResponse.json({ error: 'Admin ID is required.' }, { status: 400 });
    }

    // Prevent self-deletion
    const targetAdmin = await query('SELECT email FROM admins WHERE id = ?', [id]) as any[];
    if (targetAdmin && targetAdmin.length > 0 && targetAdmin[0].email === session.email) {
      return NextResponse.json({ error: 'You cannot delete your own account.' }, { status: 403 });
    }

    await execute('DELETE FROM admins WHERE id = ?', [id]);

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error('[admin/admins] DELETE error:', err?.message ?? err);
    return NextResponse.json({ error: 'Failed to delete admin.' }, { status: 500 });
  }
}
