import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { generateAdminToken } from '@/lib/auth';
import { isValidEmail, isValidPassword, sanitizeString } from '@/lib/validation';
import { checkRateLimit, getRateLimitIdentifier, rateLimitError, RATE_LIMITS } from '@/lib/rate-limit';

export async function POST(request: NextRequest) {
  try {
    // Rate limit admin login attempts
    const identifier = `admin-auth:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.auth);
    if (!rateLimit.allowed) {
      return rateLimitError(rateLimit.resetTime);
    }

    const body = await request.json();
    const { email, password } = body;

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

    // Validate email format
    if (!isValidEmail(email)) {
      return NextResponse.json(
        { success: false, error: 'Invalid email format' },
        { status: 400 }
      );
    }

    // Validate password format
    const passwordCheck = isValidPassword(password);
    if (!passwordCheck.valid) {
      return NextResponse.json(
        { success: false, error: passwordCheck.errors.join('. ') },
        { status: 400 }
      );
    }

    // Check for admin credentials
    // First try database lookup in User table - check multiple possible admin roles
    const normalizedEmail = email.trim().toLowerCase();
    const user = await db.user.findFirst({
      where: {
        email: normalizedEmail,
        OR: [
          { roles: 'admin' },
          { roles: 'super_admin' },
          { roles: 'houseOwner' },
          { roles: 'shopOwner' },
          { roles: 'student' },
        ],
      },
    });

    // Verify password using base64 hash comparison (consistent with /api/auth)
    const hashPassword = (pw: string) => Buffer.from(pw).toString('base64');

    if (user && user.password === hashPassword(password)) {
      const token = generateAdminToken({ id: user.id, role: 'super_admin', source: 'user' });
      return NextResponse.json({
        success: true,
        admin: {
          id: user.id,
          name: user.name,
          email: user.email,
          role: 'super_admin',
          token,
          permissions: {
            canManageUsers: true,
            canManageHouses: true,
            canManageShops: true,
            canManageProducts: true,
            canManageOrders: true,
            canManageMCQ: true,
            canManageCommunity: true,
            canSendNotification: true,
            canViewAnalytics: true,
            canManageTeam: true,
          },
        },
      });
    }

    // Check TeamMember table for team admin login
    const teamMember = await db.teamMember.findUnique({
      where: { email: normalizedEmail },
    });

    if (teamMember) {
      // Team member must be active to log in
      if (!teamMember.isActive) {
        return NextResponse.json(
          { success: false, error: 'Your account has been suspended. Contact the super admin.' },
          { status: 403 }
        );
      }

      // Decode the stored base64 password and compare
      const decodedPassword = Buffer.from(teamMember.password, 'base64').toString('utf-8');

      if (decodedPassword === password) {
        const role = teamMember.role === 'super_admin' ? 'super_admin' : 'team_admin';
        const token = generateAdminToken({ id: teamMember.id, role, source: 'team' });
        return NextResponse.json({
          success: true,
          admin: {
            id: teamMember.id,
            name: teamMember.name,
            email: teamMember.email,
            avatar: teamMember.avatar,
            phone: teamMember.phone,
            role,
            token,
            permissions: {
              canManageUsers: teamMember.canManageUsers,
              canManageHouses: teamMember.canManageHouses,
              canManageShops: teamMember.canManageShops,
              canManageProducts: teamMember.canManageProducts,
              canManageOrders: teamMember.canManageOrders,
              canManageMCQ: teamMember.canManageMCQ,
              canManageCommunity: teamMember.canManageCommunity,
              canSendNotification: teamMember.canSendNotification,
              canViewAnalytics: teamMember.canViewAnalytics,
              canManageTeam: teamMember.canManageTeam,
            },
          },
        });
      }
    }

    // Fallback: Hardcoded super admin for initial setup
    // This ensures admin can always log in even if DB hasn't been seeded yet
    const HARDCODED_ADMINS = [
      { email: 'admin@needyfy.com', password: 'Needyfy@2025', name: 'Super Admin', role: 'super_admin' },
      { email: 'superadmin@needyfy.com', password: 'SuperAdmin@2025', name: 'Super Admin', role: 'super_admin' },
    ];

    const hardcodedAdmin = HARDCODED_ADMINS.find(
      (a) => a.email === normalizedEmail && a.password === password
    );

    if (hardcodedAdmin) {
      // Try to create this admin in the DB for future logins
      try {
        const hashPw = (pw: string) => Buffer.from(pw).toString('base64');
        await db.user.upsert({
          where: { email: hardcodedAdmin.email },
          update: {},
          create: {
            name: hardcodedAdmin.name,
            email: hardcodedAdmin.email,
            password: hashPw(hardcodedAdmin.password),
            roles: 'super_admin',
            isVerified: true,
          },
        });
      } catch (dbErr) {
        console.error('Failed to create admin in DB:', dbErr);
      }

      const token = generateAdminToken({ id: `hardcoded-${hardcodedAdmin.email}`, role: hardcodedAdmin.role, source: 'hardcoded' });
      return NextResponse.json({
        success: true,
        admin: {
          id: `hardcoded-${hardcodedAdmin.email}`,
          name: hardcodedAdmin.name,
          email: hardcodedAdmin.email,
          role: hardcodedAdmin.role,
          token,
          permissions: {
            canManageUsers: true,
            canManageHouses: true,
            canManageShops: true,
            canManageProducts: true,
            canManageOrders: true,
            canManageMCQ: true,
            canManageCommunity: true,
            canSendNotification: true,
            canViewAnalytics: true,
            canManageTeam: true,
          },
        },
      });
    }

    return NextResponse.json(
      { success: false, error: 'Invalid admin credentials' },
      { status: 401 }
    );
  } catch (error) {
    console.error('Admin auth error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
