import { Router } from 'express';
import type { Request, Response } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { prisma } from '../../config/database';
import { friendshipService } from './friendship.service';
import { blockService } from './block.service';
import { messagingService } from './messaging.service';
import { checkSocialEnabled } from './social.middleware';

/** Own profile — includes email */
const OWN_PROFILE_SELECT = {
  id: true,
  name: true,
  email: true,
  role: true,
  createdAt: true,
} as const;

/** Other users' profiles — email stripped to prevent harvesting */
const PROFILE_SELECT = {
  id: true,
  name: true,
  role: true,
  createdAt: true,
} as const;

const router = Router();
router.use(authenticate);
router.use(checkSocialEnabled);

/** GET /api/social/profile/me — own profile summary */
router.get('/me', async (req: Request, res: Response) => {
  try {
    const userId = req.user!.id;

    const [user, friendCount, pendingCount, privacy] = await Promise.all([
      prisma.user.findUnique({ where: { id: userId }, select: OWN_PROFILE_SELECT }),
      prisma.friendship.count({
        where: {
          OR: [
            { userId, status: 'accepted' },
            { friendId: userId, status: 'accepted' },
          ],
        },
      }),
      prisma.friendship.count({
        where: { friendId: userId, status: 'pending' },
      }),
      prisma.privacySettings.findUnique({ where: { userId } }),
    ]);

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

    // Volunteer stats
    const [shiftSignups, canvassVisits] = await Promise.all([
      prisma.shiftSignup.count({ where: { userId } }),
      prisma.canvassVisit.count({
        where: { session: { userId } },
      }),
    ]);

    res.json({
      user,
      stats: { friendCount, pendingReceived: pendingCount, shiftSignups, canvassVisits },
      privacy: privacy || null,
    });
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'PROFILE_ERROR' } });
  }
});

/** GET /api/social/profile/:userId — view another user's profile (privacy-filtered) */
router.get('/:userId', async (req: Request, res: Response) => {
  try {
    const targetUserId = req.params.userId as string;
    const viewerId = req.user!.id;

    // Check if blocked
    const blocked = await blockService.isBlocked(viewerId, targetUserId);
    if (blocked) {
      res.status(404).json({ error: { message: 'User not found', code: 'NOT_FOUND' } });
      return;
    }

    const [user, privacy, friendshipStatus, mutualFriends] = await Promise.all([
      prisma.user.findUnique({ where: { id: targetUserId }, select: PROFILE_SELECT }),
      prisma.privacySettings.findUnique({ where: { userId: targetUserId } }),
      friendshipService.getFriendshipStatus(viewerId, targetUserId),
      friendshipService.getMutualFriends(viewerId, targetUserId),
    ]);

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

    const friendCount = await prisma.friendship.count({
      where: {
        OR: [
          { userId: targetUserId, status: 'accepted' },
          { friendId: targetUserId, status: 'accepted' },
        ],
      },
    });

    // Privacy-filtered stats (only show if showInFriendActivity is true or not set)
    let stats: Record<string, number> | null = null;
    if (privacy?.showInFriendActivity !== false) {
      const [shiftSignups, canvassVisits] = await Promise.all([
        prisma.shiftSignup.count({ where: { userId: targetUserId } }),
        prisma.canvassVisit.count({
          where: { session: { userId: targetUserId } },
        }),
      ]);
      stats = { shiftSignups, canvassVisits };
    }

    res.json({
      user,
      friendCount,
      stats,
      friendshipStatus,
      mutualFriends,
    });
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'PROFILE_ERROR' } });
  }
});

/** POST /api/social/profile/:userId/dm — Open DM channel with a friend */
router.post('/:userId/dm', async (req: Request, res: Response) => {
  try {
    const userId = req.user!.id;
    const friendId = req.params.userId as string;
    const result = await messagingService.openDM(userId, friendId);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message } });
  }
});

export { router as profileRouter };
