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

const PERMISSION_FIELDS = [
  'canManageUsers', 'canManageHouses', 'canManageShops', 'canManageProducts',
  'canManageOrders', 'canManageMCQ', 'canManageCommunity', 'canSendNotification',
  'canViewAnalytics', 'canManageTeam',
] as const;

type PermissionField = (typeof PERMISSION_FIELDS)[number];

export async function GET(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageTeam');
    if ('error' in authResult) return authResult.error;
    const members = await db.teamMember.findMany({
      orderBy: { createdAt: 'desc' },
      select: {
        id: true, name: true, email: true, avatar: true, phone: true, role: true,
        isActive: true, createdById: true, canManageUsers: true, canManageHouses: true,
        canManageShops: true, canManageProducts: true, canManageOrders: true,
        canManageMCQ: true, canManageCommunity: true, canSendNotification: true,
        canViewAnalytics: true, canManageTeam: true, createdAt: true, updatedAt: true,
      },
    });
    return NextResponse.json({ success: true, members });
  } catch (error) {
    console.error('Team members fetch error:', error);
    return NextResponse.json({ success: false, error: 'Failed to fetch team members' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageTeam');
    if ('error' in authResult) return authResult.error;
    const identifier = `admin-team-post:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.adminWrite);
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);
    const body = await request.json();
    const { name, email, password, phone, role, createdById, ...rest } = body;
    if (!name || !email || !password || !createdById) {
      return NextResponse.json({ success: false, error: 'Name, email, password, and createdById are required' }, { status: 400 });
    }
    if (!isValidName(name)) return NextResponse.json({ success: false, error: 'Invalid name' }, { status: 400 });
    if (!isValidEmail(email)) return NextResponse.json({ success: false, error: 'Invalid email' }, { status: 400 });
    if (password.length < 6) return NextResponse.json({ success: false, error: 'Password must be at least 6 characters' }, { status: 400 });
    const existing = await db.teamMember.findUnique({ where: { email: sanitizeString(email) } });
    if (existing) return NextResponse.json({ success: false, error: 'Email already exists' }, { status: 409 });
    const existingUser = await db.user.findUnique({ where: { email: sanitizeString(email) } });
    if (existingUser) return NextResponse.json({ success: false, error: 'Email registered as user' }, { status: 409 });
    const encodedPassword = Buffer.from(password).toString('base64');
    const validRoles = ['super_admin', 'admin', 'moderator', 'editor', 'viewer', 'team_admin'];
    const memberRole = role && validRoles.includes(role) ? role : 'team_admin';
    const permissionData: Record<PermissionField, boolean> = {
      canManageUsers: typeof rest.canManageUsers === 'boolean' ? rest.canManageUsers : true,
      canManageHouses: typeof rest.canManageHouses === 'boolean' ? rest.canManageHouses : true,
      canManageShops: typeof rest.canManageShops === 'boolean' ? rest.canManageShops : true,
      canManageProducts: typeof rest.canManageProducts === 'boolean' ? rest.canManageProducts : true,
      canManageOrders: typeof rest.canManageOrders === 'boolean' ? rest.canManageOrders : true,
      canManageMCQ: typeof rest.canManageMCQ === 'boolean' ? rest.canManageMCQ : true,
      canManageCommunity: typeof rest.canManageCommunity === 'boolean' ? rest.canManageCommunity : true,
      canSendNotification: typeof rest.canSendNotification === 'boolean' ? rest.canSendNotification : true,
      canViewAnalytics: typeof rest.canViewAnalytics === 'boolean' ? rest.canViewAnalytics : true,
      canManageTeam: typeof rest.canManageTeam === 'boolean' ? rest.canManageTeam : false,
    };
    const member = await db.teamMember.create({
      data: { name: sanitizeString(name), email: sanitizeString(email), password: encodedPassword, phone: phone ? sanitizeString(phone) : null, role: memberRole, createdById, ...permissionData },
      select: { id: true, name: true, email: true, avatar: true, phone: true, role: true, isActive: true, createdById: true, canManageUsers: true, canManageHouses: true, canManageShops: true, canManageProducts: true, canManageOrders: true, canManageMCQ: true, canManageCommunity: true, canSendNotification: true, canViewAnalytics: true, canManageTeam: true, createdAt: true, updatedAt: true },
    });
    return NextResponse.json({ success: true, member }, { status: 201 });
  } catch (error) {
    console.error('Team member create error:', error);
    return NextResponse.json({ success: false, error: 'Failed to create team member' }, { status: 500 });
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageTeam');
    if ('error' in authResult) return authResult.error;
    const body = await request.json();
    const { teamMemberId, isActive, name, phone, role, ...rest } = body;
    if (!teamMemberId) return NextResponse.json({ success: false, error: 'teamMemberId is required' }, { status: 400 });
    const existing = await db.teamMember.findUnique({ where: { id: teamMemberId } });
    if (!existing) return NextResponse.json({ success: false, error: 'Team member not found' }, { status: 404 });
    if (existing.role === 'super_admin' && !isSuperAdminSession(authResult.session)) {
      return NextResponse.json({ success: false, error: 'Only super admins can modify other super admins' }, { status: 403 });
    }
    const updateData: Record<string, unknown> = {};
    if (typeof isActive === 'boolean') updateData.isActive = isActive;
    if (name !== undefined) updateData.name = sanitizeString(name);
    if (phone !== undefined) updateData.phone = phone ? sanitizeString(phone) : null;
    if (role !== undefined) {
      const validRoles = ['super_admin', 'admin', 'moderator', 'editor', 'viewer', 'team_admin'];
      if (!validRoles.includes(role)) return NextResponse.json({ success: false, error: 'Invalid role' }, { status: 400 });
      updateData.role = role;
    }
    for (const field of PERMISSION_FIELDS) {
      if (typeof rest[field] === 'boolean') updateData[field] = rest[field];
    }
    const member = await db.teamMember.update({
      where: { id: teamMemberId }, data: updateData,
      select: { id: true, name: true, email: true, avatar: true, phone: true, role: true, isActive: true, createdById: true, canManageUsers: true, canManageHouses: true, canManageShops: true, canManageProducts: true, canManageOrders: true, canManageMCQ: true, canManageCommunity: true, canSendNotification: true, canViewAnalytics: true, canManageTeam: true, createdAt: true, updatedAt: true },
    });
    return NextResponse.json({ success: true, member });
  } catch (error) {
    console.error('Team member update error:', error);
    return NextResponse.json({ success: false, error: 'Failed to update team member' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission(request, 'canManageTeam');
    if ('error' in authResult) return authResult.error;
    const { teamMemberId } = await request.json();
    if (!teamMemberId) return NextResponse.json({ success: false, error: 'teamMemberId is required' }, { status: 400 });
    const existing = await db.teamMember.findUnique({ where: { id: teamMemberId } });
    if (!existing) return NextResponse.json({ success: false, error: 'Team member not found' }, { status: 404 });
    if (existing.role === 'super_admin') return NextResponse.json({ success: false, error: 'Cannot delete super admins' }, { status: 403 });
    await db.teamMember.delete({ where: { id: teamMemberId } });
    return NextResponse.json({ success: true, message: 'Team member deleted' });
  } catch (error) {
    console.error('Team member delete error:', error);
    return NextResponse.json({ success: false, error: 'Failed to delete team member' }, { status: 500 });
  }
}
