import prisma from '../lib/prisma.js';
import { getIo } from '../lib/socket.js';
import {
  AUTO_ARCHIVE_SETTINGS_KEY,
  DEFAULT_AUTO_ARCHIVE_SETTINGS,
  AutoArchiveSettings,
} from '../config/autoArchive.js';
import { logActivity } from '../utils/activityLog.js';

const HOURS = 60 * 60 * 1000;

async function getAutoArchiveSettings(): Promise<AutoArchiveSettings> {
  const record = await prisma.setting.upsert({
    where: { key: AUTO_ARCHIVE_SETTINGS_KEY },
    update: {},
    create: {
      key: AUTO_ARCHIVE_SETTINGS_KEY,
      value: DEFAULT_AUTO_ARCHIVE_SETTINGS,
    },
  });

  const stored = (record.value as Partial<AutoArchiveSettings>) || {};
  return {
    ...DEFAULT_AUTO_ARCHIVE_SETTINGS,
    ...stored,
  };
}

async function sendOwnerMessage(ownerId: string, propertyId: string, content: string, adminId: string) {
  // Find or create a conversation between admin and owner on this property
  let conversation = await prisma.conversation.findFirst({
    where: {
      propertyId,
      participants: { some: { userId: ownerId } },
    },
    include: { participants: true },
  });

  if (!conversation) {
    conversation = await prisma.conversation.create({
      data: {
        property: { connect: { id: propertyId } },
        creator: { connect: { id: adminId } },
        participants: {
          create: [
            { user: { connect: { id: adminId } } },
            { user: { connect: { id: ownerId } } },
          ],
        },
      },
      include: { participants: true },
    });
  }

  // Send the message
  const message = await prisma.message.create({
    data: {
      conversationId: conversation.id,
      senderId: adminId,
      recipientId: ownerId,
      content,
    },
  });

  await prisma.conversation.update({
    where: { id: conversation.id },
    data: { lastMessageAt: message.createdAt },
  });

  // Emit socket events
  const io = getIo();
  if (io) {
    io.to(`user:${ownerId}`).emit('message:new', {
      conversationId: conversation.id,
      message: {
        id: message.id,
        senderId: message.senderId,
        recipientId: message.recipientId,
        content: message.content,
        createdAt: message.createdAt,
      },
    });
    io.to(`user:${adminId}`).emit('message:new', {
      conversationId: conversation.id,
      message: {
        id: message.id,
        senderId: message.senderId,
        recipientId: message.recipientId,
        content: message.content,
        createdAt: message.createdAt,
      },
    });
  }

  // Send FCM push notification
  const { sendMessageNotification } = await import('../lib/fcm.js');
  const property = await prisma.property.findUnique({
    where: { id: propertyId },
    select: { title: true },
  });

  sendMessageNotification(
    ownerId,
    'Admin',
    content,
    conversation.id,
    property?.title || undefined
  ).catch((error) => {
    console.error('[AUTO_ARCHIVE] Failed to send FCM notification:', error);
  });
}

export const startAutoArchiveJob = () => {
  let timer: NodeJS.Timeout | undefined;

  const scheduleNext = (hours: number) => {
    const intervalMs = Math.max(1, hours || DEFAULT_AUTO_ARCHIVE_SETTINGS.frequencyHours) * HOURS;
    timer = setTimeout(run, intervalMs);
  };

  const run = async () => {
    let settings = DEFAULT_AUTO_ARCHIVE_SETTINGS;
    try {
      settings = await getAutoArchiveSettings();
      if (!settings.enforced) {
        return;
      }

      const now = new Date();
      const expiryThreshold = new Date(now.getTime() - settings.maxActiveDays * 24 * 60 * 60 * 1000);
      const reminderThreshold =
        settings.graceDays && settings.graceDays > 0
          ? new Date(
              now.getTime() - (settings.maxActiveDays - settings.graceDays) * 24 * 60 * 60 * 1000,
            )
          : null;

      // Find an admin to send messages from
      const admin = await prisma.user.findFirst({ where: { role: 'ADMIN' } });

      // Reminders for soon-to-expire listings
      if (admin && reminderThreshold) {
        const expiring = await prisma.property.findMany({
          where: {
            status: 'ACTIVE',
            publishedAt: { lte: reminderThreshold },
            autoArchiveReminderSentAt: null,
          },
          select: { id: true, ownerId: true, title: true },
          take: 50,
        });

        for (const p of expiring) {
          const content = `Reminder: Your listing "${p.title}" will be auto-archived soon. You can reactivate it if it remains available.`;
          await sendOwnerMessage(p.ownerId, p.id, content, admin.id);
          await prisma.property.update({
            where: { id: p.id },
            data: { autoArchiveReminderSentAt: now },
          });
        }
      }

      // Auto-archive expired listings
      const expired = await prisma.property.findMany({
        where: {
          status: 'ACTIVE',
          publishedAt: { lte: expiryThreshold },
        },
        select: { id: true, ownerId: true, title: true },
        take: 100,
      });

      for (const p of expired) {
        await prisma.property.update({
          where: { id: p.id },
          data: { status: 'ARCHIVED' },
        });

        const owner = await prisma.user.findUnique({ where: { id: p.ownerId }, select: { role: true } });
        if (owner?.role === 'AGENT') {
          try {
            const { recalcAgentUsageForCurrentPeriod } = await import('../utils/agentUsage.js');
            await recalcAgentUsageForCurrentPeriod(p.ownerId, now);
          } catch (err) {
            console.error('Failed to recalc AgentUsage after auto-archive for agent', p.ownerId, err);
          }
        }

        await logActivity({
          userId: p.ownerId,
          activityType: 'LISTING_AUTO_ARCHIVED',
          resourceId: p.id,
          resourceType: 'property',
          metadata: { autoArchived: true },
        });

        if (admin) {
          const content = `Your listing "${p.title}" was auto-archived after ${settings.maxActiveDays} days. You can reactivate it anytime.`;
          await sendOwnerMessage(p.ownerId, p.id, content, admin.id);
        }
      }
    } catch (err) {
      console.error('Auto-archive job failed:', err);
    } finally {
      scheduleNext(settings.frequencyHours ?? DEFAULT_AUTO_ARCHIVE_SETTINGS.frequencyHours);
    }
  };

  run();

  return () => {
    if (timer) {
      clearTimeout(timer);
    }
  };
};

