import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { BillingService } from './billing.service';

/**
 * The monthly billing run. Replaces the legacy dead cron endpoint (a public GET
 * guarded by APP_NAME with a dd() in the middle). Runs in-process via the Nest
 * scheduler, generating DRAFT invoices for every active lease — a human still
 * reviews and issues them. The same logic is exposed as invoices.runDrafts for
 * on-demand runs.
 */
@Injectable()
export class BillingScheduler {
  private readonly logger = new Logger(BillingScheduler.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly billing: BillingService,
  ) {}

  // 01:00 every day — reconcile the lease lifecycle promptly (end finished
  // leases, activate scheduled renewals, carry deposits over) so a lease's stored
  // status never lags more than a day, independent of the monthly billing run.
  @Cron('0 1 * * *', { name: 'daily-lease-transition' })
  async dailyTransition(): Promise<void> {
    await this.transitionAllOrgs();
  }

  // 02:00 on the 1st of every month.
  @Cron('0 2 1 * *', { name: 'monthly-billing-run' })
  async monthlyRun(): Promise<void> {
    const period = currentPeriod();
    // Reconcile the lease lifecycle before billing so the run sees the correct
    // set of active leases (idempotent with the daily job above).
    await this.transitionAllOrgs();
    const orgs = await this.prisma.organization.findMany({
      where: { deletedAt: null },
      select: { id: true },
    });
    for (const org of orgs) {
      const result = await this.billing.generateDraftsForPeriod({ organizationId: org.id, period });
      this.logger.log(
        `Billing run ${period} org=${org.id}: ${result.created} drafts created, ${result.skipped} skipped of ${result.leaseCount} active leases`,
      );
    }
  }

  // 09:00 Hong Kong every day — issue the debit notes whose scheduled day has
  // arrived. Pinned to Hong Kong (unlike the jobs above, whose period arithmetic
  // is host-local and must stay that way) so "goes out on the 28th" means the
  // morning of the 28th wherever this runs, and so a failure lands in office
  // hours: this job burns a number, posts to the ledger and emails a tenant.
  @Cron('0 9 * * *', { name: 'scheduled-invoice-issue', timeZone: 'Asia/Hong_Kong' })
  async scheduledIssue(): Promise<void> {
    try {
      const res = await this.billing.issueScheduled();
      for (const f of res.failures) {
        this.logger.warn(`Scheduled issue failed org=${f.organizationId} invoice=${f.invoiceId}: ${f.message}`);
      }
      if (res.due > 0) {
        this.logger.log(`Scheduled issue: ${res.issued} issued, ${res.failures.length} failed of ${res.due} due`);
      }
    } catch (e) {
      // Without this a transient error in the initial query becomes an unhandled
      // rejection — the cron library only guards the promise it is handed.
      this.logger.error(`Scheduled issue run failed: ${e instanceof Error ? e.message : e}`);
    }
  }

  /** End finished leases, activate scheduled renewals, and carry deposits over
   * for every organization. Idempotent — safe to run daily and again before the
   * monthly billing run. */
  private async transitionAllOrgs(): Promise<void> {
    const orgs = await this.prisma.organization.findMany({
      where: { deletedAt: null },
      select: { id: true },
    });
    for (const org of orgs) {
      const tr = await this.billing.transitionLeases({ organizationId: org.id, asOf: new Date() });
      if (tr.activated || tr.ended || tr.depositsMoved) {
        this.logger.log(`Lease transition org=${org.id}: ${tr.activated} activated, ${tr.ended} ended, ${tr.depositsMoved} deposit(s) carried over`);
      }
    }
  }
}

function currentPeriod(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
