import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';

/**
 * BRAND MAILBOX HEALTH CHECK
 * ═══════════════════════════════════════════════════════════
 * Runs once at application startup. Verifies that exactly one
 * email_settings row is tagged for each brand the client portal
 * depends on (CLIENT_PORTAL_TQS, CLIENT_PORTAL_QRS).
 *
 * Why this exists:
 *   The original bug (QRS invites silently sent from the wrong
 *   mailbox for weeks) produced ZERO errors anywhere — no failed
 *   request, no exception, nothing in the logs to search for.
 *   The only way to have caught it sooner was to check the
 *   *configuration* itself, proactively, before real users hit it.
 *
 * Behavior:
 *   - Logs a clear ERROR (and can be wired to page/alert) if a
 *     brand_key is missing or duplicated.
 *   - Does NOT crash the whole app on its own — client-portal
 *     invites will already fail cleanly (BadRequestException) if
 *     this is broken, so email-sending elsewhere in the app isn't
 *     taken down by a client-portal-specific config problem.
 *     If you want a hard boot failure instead, throw in the
 *     `if (problems.length)` block below.
 */
@Injectable()
export class BrandMailboxHealthCheckService implements OnApplicationBootstrap {
  private readonly logger = new Logger('BrandMailboxHealthCheck');

  private static readonly REQUIRED_BRAND_KEYS = [
    'CLIENT_PORTAL_TQS',
    'CLIENT_PORTAL_QRS',
  ];

  constructor(
    @InjectDataSource('scheme_dbs')
    private readonly dataSource: DataSource,
  ) {}

  async onApplicationBootstrap(): Promise<void> {
    const problems: string[] = [];

    for (const brandKey of BrandMailboxHealthCheckService.REQUIRED_BRAND_KEYS) {
      const rows = await this.dataSource.query(
        `SELECT id, from_email, user_id FROM email_settings WHERE brand_key = ?`,
        [brandKey],
      );

      if (rows.length === 0) {
        problems.push(`Missing: no mailbox tagged brand_key='${brandKey}'`);
      } else if (rows.length > 1) {
        problems.push(
          `Duplicate: ${rows.length} mailboxes tagged brand_key='${brandKey}' (ids: ${rows
            .map((r: any) => r.id)
            .join(', ')})`,
        );
      } else if (!rows[0].user_id) {
        problems.push(`Unlinked: mailbox '${rows[0].from_email}' (brand_key='${brandKey}') has no user_id`);
      }
    }

    if (problems.length > 0) {
      this.logger.error(
        `❌ CLIENT PORTAL BRAND MAILBOX MISCONFIGURATION DETECTED AT STARTUP:\n` +
        problems.map((p) => `   - ${p}`).join('\n') +
        `\n   Client-portal invite/OTP emails WILL fail or send from the wrong address until fixed.`,
      );
      // Uncomment to hard-fail deployment instead of just logging:
      // throw new Error('Client portal brand mailbox misconfiguration — see logs above.');
    } else {
      this.logger.log(`✓ Brand mailbox configuration OK (${BrandMailboxHealthCheckService.REQUIRED_BRAND_KEYS.join(', ')})`);
    }
  }
}
