import { Router, Request, Response } from 'express';
import prisma from '../lib/prisma.js';
import { generateToken } from '../utils/jwt.js';
import { z } from 'zod';
import { validate } from '../utils/validation.js';
import bcrypt from 'bcryptjs';
import { getUserFeatureKeys, isStaffRole, authenticateToken, AuthRequest } from '../middleware/auth.middleware.js';
import { createLoginSessionFromRequest, logActivity } from '../utils/activityLog.js';

const router = Router();

// Register schema
const registerSchema = z.object({
  body: z.object({
    email: z.string().email().optional(),
    phone: z.string().min(10).optional(),
    password: z.string().min(6),
    firstName: z.string().optional(),
    lastName: z.string().optional(),
    role: z.enum(['OWNER', 'BUYER', 'AGENT']).default('BUYER'),
    countryCode: z.string().optional().default('251'),
    country: z.string().optional().default('Ethiopia'),
  }).refine(data => data.email || data.phone, {
    message: 'Either email or phone is required',
  }),
});

// Login schema
const loginSchema = z.object({
  body: z.object({
    email: z.string().email().optional(),
    phone: z.string().optional(),
    password: z.string().min(1),
  }).refine(data => data.email || data.phone, {
    message: 'Either email or phone is required',
  }),
});

// Register endpoint
router.post('/register', validate(registerSchema), async (req: Request, res: Response) => {
  try {
    const { email, phone, password, firstName, lastName, role, countryCode, country } = req.body;

    // Check if user already exists
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [
          email ? { email } : {},
          phone ? { phone } : {},
        ].filter(obj => Object.keys(obj).length > 0),
      },
    });

    if (existingUser) {
      return res.status(400).json({ 
        error: 'User already exists with this email or phone' 
      });
    }

    // Hash password
    const passwordHash = await bcrypt.hash(password, 10);

    // Create user
    const user = await prisma.user.create({
      data: {
        email,
        phone,
        passwordHash,
        firstName,
        lastName,
        role: role || 'BUYER',
        // Optional location metadata – Prisma model has these fields with defaults,
        // so we only override them if provided.
        countryCode,
        country,
      },
      select: {
        id: true,
        email: true,
        phone: true,
        firstName: true,
        lastName: true,
        role: true,
        verified: true,
        createdAt: true,
      },
    });

    // Generate token
    const token = generateToken({
      userId: user.id,
      role: user.role,
      email: user.email || undefined,
    });

    const { userDeviceId } = await createLoginSessionFromRequest(user.id, req);
    await logActivity({
      userId: user.id,
      activityType: 'ACCOUNT_CREATED',
      req,
      userDeviceId,
    });

    res.status(201).json({
      message: 'User registered successfully',
      user,
      token,
    });
  } catch (error: any) {
    console.error('Register error:', error);
    res.status(500).json({ 
      error: 'Registration failed',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// Login endpoint
router.post('/login', validate(loginSchema), async (req: Request, res: Response) => {
  try {
    const { email, phone, password } = req.body;

    // Find user
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          email ? { email } : {},
          phone ? { phone } : {},
        ].filter(obj => Object.keys(obj).length > 0),
      },
    });

    if (!user) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Check password
    const isValidPassword = await bcrypt.compare(password, user.passwordHash);

    if (!isValidPassword) {
      return res.status(401).json({ error: 'Invalid credentials' });
    }

    // Update last login
    await prisma.user.update({
      where: { id: user.id },
      data: { lastLogin: new Date() },
    });

    // Generate token
    const token = generateToken({
      userId: user.id,
      role: user.role,
      email: user.email || undefined,
    });

    const { userDeviceId } = await createLoginSessionFromRequest(user.id, req);
    await logActivity({
      userId: user.id,
      activityType: 'LOGIN',
      req,
      userDeviceId,
    });

    const features =
      user.role === 'ADMIN'
        ? (await prisma.adminFeature.findMany({ select: { key: true }, orderBy: { key: 'asc' } })).map((f) => f.key)
        : isStaffRole(user.role)
          ? await getUserFeatureKeys(user.id)
          : undefined;

    res.json({
      message: 'Login successful',
      user: {
        id: user.id,
        email: user.email,
        phone: user.phone,
        firstName: user.firstName,
        lastName: user.lastName,
        role: user.role,
        verified: user.verified,
      },
      token,
      ...(features ? { features } : {}),
    });
  } catch (error: any) {
    console.error('Login error:', error);
    res.status(500).json({ 
      error: 'Login failed',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// Update profile schema
const updateProfileSchema = z.object({
  body: z.object({
    firstName: z.string().optional(),
    lastName: z.string().optional(),
    email: z.string().email().optional(),
  }),
});

// Change password schema
const changePasswordSchema = z.object({
  body: z.object({
    currentPassword: z.string().min(1),
    newPassword: z.string().min(6),
  }),
});

// GET /api/auth/me - Get current authenticated user
router.get('/me', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        email: true,
        phone: true,
        firstName: true,
        lastName: true,
        role: true,
        verified: true,
        dateOfBirth: true,
        profilePicture: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    res.json(user);
  } catch (error: any) {
    console.error('Get current user error:', error);
    res.status(500).json({ 
      error: 'Failed to get user',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// PUT /api/auth/me - Update current authenticated user profile
router.put('/me', authenticateToken, validate(updateProfileSchema), async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const { firstName, lastName, email } = req.body;

    // Check if email is already taken by another user
    if (email) {
      const existingUser = await prisma.user.findFirst({
        where: {
          AND: [
            { id: { not: userId } },
            { email },
          ],
        },
      });

      if (existingUser) {
        return res.status(400).json({ 
          error: 'Email is already in use by another account' 
        });
      }
    }

    // Update user (phone is not editable)
    const updateData: any = {};
    if (firstName !== undefined) updateData.firstName = firstName || null;
    if (lastName !== undefined) updateData.lastName = lastName || null;
    if (email !== undefined) updateData.email = email || null;

    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data: updateData,
      select: {
        id: true,
        email: true,
        phone: true,
        firstName: true,
        lastName: true,
        role: true,
        verified: true,
        profilePicture: true,
        createdAt: true,
        updatedAt: true,
      },
    });

    await logActivity({
      userId,
      activityType: 'PROFILE_UPDATED',
      req: req as Request,
    });

    res.json(updatedUser);
  } catch (error: any) {
    console.error('Update profile error:', error);
    res.status(500).json({ 
      error: 'Failed to update profile',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// PUT /api/auth/change-password - Change user password
router.put('/change-password', authenticateToken, validate(changePasswordSchema), async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const { currentPassword, newPassword } = req.body;

    // Get user with password hash
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: { id: true, passwordHash: true },
    });

    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // Verify current password
    const isValidPassword = await bcrypt.compare(currentPassword, user.passwordHash);
    if (!isValidPassword) {
      return res.status(400).json({ error: 'Current password is incorrect' });
    }

    // Hash new password
    const newPasswordHash = await bcrypt.hash(newPassword, 10);

    // Update password
    await prisma.user.update({
      where: { id: userId },
      data: { passwordHash: newPasswordHash },
    });

    await logActivity({
      userId,
      activityType: 'PASSWORD_CHANGED',
      req: req as Request,
    });

    res.json({ message: 'Password changed successfully' });
  } catch (error: any) {
    console.error('Change password error:', error);
    res.status(500).json({ 
      error: 'Failed to change password',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// DELETE /api/auth/account - Soft delete current user's account
router.delete('/account', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const existing = await prisma.user.findUnique({
      where: { id: userId },
      select: { id: true, email: true, phone: true, role: true, isActive: true },
    });

    if (!existing) {
      return res.status(404).json({ error: 'User not found' });
    }

    // Best-effort scrubbing of PII: clear email/phone, mark inactive/blocked.
    const anonymizedEmail = existing.email ? `deleted+${existing.id}@cool.et` : null;

    await prisma.$transaction(async (tx) => {
      await tx.user.update({
        where: { id: userId },
        data: {
          email: anonymizedEmail,
          phone: null,
          isActive: false,
          isBlocked: true,
          blockedReason: 'User requested account deletion via mobile app',
        },
      });

      // Remove FCM tokens and login sessions
      await tx.userDevice.updateMany({
        where: { userId, fcmToken: { not: null } },
        data: { fcmToken: null },
      });
      await tx.loginSession.deleteMany({ where: { userId } });

      await logActivity({
        userId,
        activityType: 'ACCOUNT_DELETED',
        req: req as Request,
      });
    });

    return res.json({ message: 'Account deleted successfully' });
  } catch (error: any) {
    console.error('Delete account error:', error);
    return res.status(500).json({
      error: 'Failed to delete account',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

export default router;


