import prisma from '../lib/prisma.js';
import { getBrokerDetectionSettings } from './activityLog.js';
import type { ListingFrequencyRule, ListingFrequencyWindow } from '../config/brokerDetection.js';

const clampScore = (n: number) => Math.max(0, Math.min(100, Math.round(n)));

const windowToMs = (window: ListingFrequencyWindow): number | null => {
  switch (window) {
    case 'HOUR':
      return 60 * 60 * 1000;
    case 'DAY':
      return 24 * 60 * 60 * 1000;
    case 'MONTH':
      return 30 * 24 * 60 * 60 * 1000;
    case 'LIFETIME':
      return null;
    default:
      return null;
  }
};

const computeWindowStart = (now: Date, window: ListingFrequencyWindow): Date | null => {
  const ms = windowToMs(window);
  if (!ms) return null;
  return new Date(now.getTime() - ms);
};

export type ListingFrequencyEvaluation = {
  rule: ListingFrequencyRule;
  windowStart: Date | null;
  listingCount: number;
  exceeded: boolean;
};

export const evaluateListingFrequencyForUser = async (userId: string, now = new Date()) => {
  const user = await prisma.user.findUnique({ where: { id: userId }, select: { role: true, verified: true } });
  if (user?.role === 'AGENT') {
    const existing = await prisma.riskScore.findUnique({
      where: { userId },
      select: { overallScore: true },
    });

    return {
      evaluations: [] as ListingFrequencyEvaluation[],
      triggered: [] as ListingFrequencyEvaluation[],
      frequencyScore: 0,
      overallScore: existing?.overallScore ?? 0,
    };
  }

  const settings = await getBrokerDetectionSettings();
  let rules = settings.listingFrequencyRules;

  // For verified owners who provide ownership proof documents, relax frequency limits slightly
  if (user?.role === 'OWNER' && user.verified) {
    try {
      const [totalProps, propsWithProof] = await Promise.all([
        prisma.property.count({ where: { ownerId: userId } }),
        prisma.property.count({ where: { ownerId: userId, ownershipProofUrl: { not: null } } }),
      ]);

      const hasStrongProof = totalProps > 0 && propsWithProof / totalProps >= 0.6;
      if (hasStrongProof) {
        // Increase maxCount and reduce score impact to lower false positives for legitimate multi-property owners
        rules = rules.map((r) => ({
          ...r,
          maxCount: Math.round(r.maxCount * 1.5),
          scoreImpact: Math.round((r.scoreImpact || 0) * 0.6),
        }));
      }
    } catch (err) {
      console.error('Broker detection verified-owner adjustment failed for user', userId, err);
    }
  }

  const evaluations: ListingFrequencyEvaluation[] = await Promise.all(
    rules.map(async (rule) => {
      const windowStart = computeWindowStart(now, rule.window);

      const listingCount = await prisma.property.count({
        where: {
          ownerId: userId,
          ...(windowStart ? { createdAt: { gte: windowStart } } : {}),
        },
      });

      return {
        rule,
        windowStart,
        listingCount,
        exceeded: listingCount > rule.maxCount,
      };
    }),
  );

  const triggered = evaluations.filter((e) => e.exceeded);
  const frequencyScore = clampScore(triggered.reduce((sum, e) => sum + (e.rule.scoreImpact || 0), 0));

  const existing = await prisma.riskScore.findUnique({
    where: { userId },
    select: {
      overallScore: true,
      similarityScore: true,
      technicalScore: true,
      dataQualityScore: true,
      networkScore: true,
      componentScores: true,
      triggeredAlerts: true,
    },
  });

  const componentScores: any = existing?.componentScores || {};
  componentScores.frequency = {
    evaluatedAt: now.toISOString(),
    rules: evaluations.map((e) => ({
      window: e.rule.window,
      maxCount: e.rule.maxCount,
      listingCount: e.listingCount,
      exceeded: e.exceeded,
      windowStart: e.windowStart ? e.windowStart.toISOString() : null,
      scoreImpact: e.rule.scoreImpact,
      riskLevel: e.rule.riskLevel,
    })),
  };

  // ---------------------------------------------
  // Device/network multi-account heuristic (no similarity)
  // ---------------------------------------------
  let computedNetworkScore = 0;
  let networkComponent: any = componentScores.network || null;

  if (settings.enableDeviceHeuristics !== false) {
    const warnThreshold = Math.max(0, Number(settings.deviceLinkedAccountWarnThreshold ?? 1));
    const highRiskThreshold = Math.max(
      warnThreshold + 1,
      Number(settings.deviceLinkedAccountHighRiskThreshold ?? 4),
    );
    const cooldownDays = Math.max(0, Number(settings.deviceHeuristicCooldownDays ?? 30));
    const maxNetworkScore = clampScore(Number(settings.deviceMaxNetworkScore ?? 80));

    try {
      // Find this user's devices
      const userDevices = await prisma.userDevice.findMany({
        where: { userId },
        select: { deviceIdHash: true },
      });

      const deviceHashes = Array.from(
        new Set(userDevices.map((d) => d.deviceIdHash).filter((h): h is string => Boolean(h))),
      );

      if (deviceHashes.length > 0) {
        // Find other users who have used the same devices
        const otherDevices = await prisma.userDevice.findMany({
          where: {
            deviceIdHash: { in: deviceHashes },
            userId: { not: userId },
          },
          select: { deviceIdHash: true, userId: true },
        });

        const accountsByDevice = new Map<string, Set<string>>();
        for (const row of otherDevices) {
          if (!row.deviceIdHash || !row.userId) continue;
          if (!accountsByDevice.has(row.deviceIdHash)) {
            accountsByDevice.set(row.deviceIdHash, new Set());
          }
          accountsByDevice.get(row.deviceIdHash)!.add(row.userId);
        }

        const linkedAccounts = new Set<string>();
        for (const [, userIds] of accountsByDevice) {
          for (const uid of userIds) {
            linkedAccounts.add(uid);
          }
        }

        const linkedAccountCount = linkedAccounts.size;

        if (linkedAccountCount >= warnThreshold && linkedAccountCount > 0) {
          computedNetworkScore = clampScore(Math.min(maxNetworkScore, linkedAccountCount * 20));

          const devicesEvidence = Array.from(accountsByDevice.entries()).map(([deviceIdHash, users]) => ({
            deviceIdHash,
            linkedUserIds: Array.from(users),
          }));

          networkComponent = {
            ...(componentScores.network || {}),
            multiAccountPerDevice: {
              evaluatedAt: now.toISOString(),
              deviceCount: deviceHashes.length,
              linkedAccountCount,
              warnThreshold,
              highRiskThreshold,
              devices: devicesEvidence,
            },
          };

          const cooldownStart = new Date(now.getTime() - cooldownDays * 24 * 60 * 60 * 1000);

          const existingAlert = await prisma.suspiciousActivity.findFirst({
            where: {
              userId,
              activityType: 'MULTIPLE_ACCOUNTS_SAME_DEVICE',
              createdAt: { gte: cooldownStart },
            },
            select: { id: true },
          });

          if (!existingAlert) {
            const riskLevel = linkedAccountCount >= highRiskThreshold ? 'CRITICAL' : 'HIGH';

            await prisma.suspiciousActivity.create({
              data: {
                userId,
                activityType: 'MULTIPLE_ACCOUNTS_SAME_DEVICE',
                riskLevel: riskLevel as any,
                evidence: {
                  evaluatedAt: now.toISOString(),
                  linkedAccountCount,
                  warnThreshold,
                  highRiskThreshold,
                  cooldownDays,
                  maxNetworkScore,
                  devices: devicesEvidence,
                },
              },
            });
          }
        }
      }
    } catch (err) {
      // Heuristic should never break main flow; log and continue
      console.error('Broker detection device heuristic error for user', userId, err);
    }
  }

  if (networkComponent) {
    componentScores.network = networkComponent;
  }

  const similarityScore = existing?.similarityScore ?? 0;
  const technicalScore = existing?.technicalScore ?? 0;
  const dataQualityScore = existing?.dataQualityScore ?? 0;
  const baseNetworkScore = existing?.networkScore ?? 0;
  const networkScore = clampScore(Math.max(baseNetworkScore, computedNetworkScore));

  const overallScore = clampScore(
    Math.max(
      frequencyScore,
      similarityScore,
      technicalScore,
      dataQualityScore,
      networkScore,
      existing?.overallScore ?? 0,
    ),
  );

  await prisma.riskScore.upsert({
    where: { userId },
    update: {
      overallScore,
      frequencyScore,
      similarityScore,
      technicalScore,
      dataQualityScore,
      networkScore,
      componentScores,
      triggeredAlerts: existing?.triggeredAlerts ?? undefined,
      lastCalculated: now,
    },
    create: {
      userId,
      overallScore,
      frequencyScore,
      similarityScore,
      technicalScore,
      dataQualityScore,
      networkScore,
      componentScores,
      triggeredAlerts: undefined,
      lastCalculated: now,
    },
  });

  await Promise.all(
    triggered.map(async (t) => {
      const activityType = `LISTING_FREQUENCY_EXCEEDED_${t.rule.window}`;
      const throttleStart = t.windowStart ?? new Date(now.getTime() - 24 * 60 * 60 * 1000);

      const existingAlert = await prisma.suspiciousActivity.findFirst({
        where: {
          userId,
          activityType,
          createdAt: { gte: throttleStart },
        },
        select: { id: true },
      });

      if (existingAlert) return;

      await prisma.suspiciousActivity.create({
        data: {
          userId,
          activityType,
          riskLevel: t.rule.riskLevel,
          evidence: {
            window: t.rule.window,
            maxCount: t.rule.maxCount,
            listingCount: t.listingCount,
            windowStart: t.windowStart ? t.windowStart.toISOString() : null,
            evaluatedAt: now.toISOString(),
            enforced: t.rule.enforced ?? false,
          },
        },
      });
    }),
  );

  return {
    evaluations,
    triggered,
    frequencyScore,
    overallScore,
  };
};

export const checkListingFrequencyEnforcement = async (userId: string, now = new Date()) => {
  const user = await prisma.user.findUnique({ where: { id: userId }, select: { role: true, verified: true } });
  if (user?.role === 'AGENT') {
    return { blocked: false as const, reason: null as string | null };
  }

  const settings = await getBrokerDetectionSettings();
  const enforcedRules = settings.listingFrequencyRules.filter((r) => r.enforced);

  if (enforcedRules.length === 0) {
    return { blocked: false as const, reason: null as string | null };
  }

  for (const rule of enforcedRules) {
    const windowStart = computeWindowStart(now, rule.window);
    const listingCount = await prisma.property.count({
      where: {
        ownerId: userId,
        ...(windowStart ? { createdAt: { gte: windowStart } } : {}),
      },
    });

    // Verified owners with ownership proof get a slightly higher cap to reduce false positives
    let effectiveMax = rule.maxCount;
    if (user?.role === 'OWNER' && user.verified) {
      try {
        const [totalProps, propsWithProof] = await Promise.all([
          prisma.property.count({ where: { ownerId: userId } }),
          prisma.property.count({ where: { ownerId: userId, ownershipProofUrl: { not: null } } }),
        ]);
        const hasStrongProof = totalProps > 0 && propsWithProof / totalProps >= 0.6;
        if (hasStrongProof) {
          effectiveMax = Math.round(rule.maxCount * 1.5);
        }
      } catch (err) {
        console.error('Broker enforcement verified-owner adjustment failed for user', userId, err);
      }
    }

    if (listingCount >= effectiveMax) {
      return {
        blocked: true as const,
        reason: `Listing limit exceeded (${rule.window}): max ${effectiveMax}`,
      };
    }
  }

  return { blocked: false as const, reason: null as string | null };
};
