import prisma from "@shieldai/db";
import { RemovalStatus } from "@shieldai/types";
import { removeBrokersService } from "./RemoveBrokersService";

const DEFAULT_SCAN_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
const VERIFICATION_DELAY_MS = 7 * 24 * 60 * 60 * 1000; // 7 days after submission

export class RemoveBrokersScheduler {
  private intervalId: NodeJS.Timeout | null = null;
  private intervalMs: number;

  constructor(intervalMs: number = DEFAULT_SCAN_INTERVAL_MS) {
    this.intervalMs = intervalMs;
  }

  isRunning(): boolean {
    return this.intervalId !== null;
  }

  start() {
    if (this.isRunning()) {
      return;
    }

    this.intervalId = setInterval(async () => {
      try {
        await this.runCycle();
      } catch (error) {
        console.error("[RemoveBrokers] Scheduler cycle error:", error);
      }
    }, this.intervalMs);

    console.log("[RemoveBrokers] Scheduler started");
  }

  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
      console.log("[RemoveBrokers] Scheduler stopped");
    }
  }

  async runCycle() {
    console.log("[RemoveBrokers] Running scheduler cycle...");

    const results = {
      processed: 0,
      verified: 0,
      errors: 0,
    };

    try {
      const processResults = await removeBrokersService.processPendingRequests();
      results.processed = processResults.length;
    } catch (error) {
      console.error("[RemoveBrokers] Process pending error:", error);
      results.errors++;
    }

    try {
      const verifyResults = await this.verifyCompletedRemovals();
      results.verified = verifyResults.length;
    } catch (error) {
      console.error("[RemoveBrokers] Verify completions error:", error);
      results.errors++;
    }

    console.log(
      `[RemoveBrokers] Cycle complete: ${JSON.stringify(results)}`,
    );

    return results;
  }

  async runScan(subscriptionId: string) {
    const subscription = await prisma.subscription.findUnique({
      where: { id: subscriptionId },
    });

    if (!subscription) {
      throw new Error("Subscription not found");
    }

    const user = await prisma.user.findUnique({
      where: { id: subscription.userId },
      select: { name: true, email: true },
    });

    if (!user?.name) {
      throw new Error("User name required for scanning");
    }

    const personalInfo = {
      fullName: user.name,
      email: user.email,
    };

    const results = await removeBrokersService.scanForListings(
      subscriptionId,
      personalInfo,
    );

    return {
      subscriptionId,
      brokersScanned: results.length,
      listingsFound: results.filter((r) => r.found).length,
      results,
    };
  }

  private async verifyCompletedRemovals() {
    const submitted = await prisma.removalRequest.findMany({
      where: {
        status: RemovalStatus.SUBMITTED,
        submittedAt: {
          lte: new Date(Date.now() - VERIFICATION_DELAY_MS),
        },
      },
    });

    const results = [];

    for (const request of submitted) {
      try {
        const verification = await removeBrokersService.verifyRemoval(
          request.id,
        );
        results.push({
          requestId: request.id,
          ...verification,
        });
      } catch (error) {
        console.error(
          `[RemoveBrokers] Verification error for ${request.id}:`,
          error,
        );
      }
    }

    return results;
  }
}

export const removeBrokersScheduler = new RemoveBrokersScheduler();
