/**
 * FormLibrarySeeder — runs once on application bootstrap.
 *
 * Inserts any stock form definitions that don't yet exist in the database.
 * Existing entries are NEVER overwritten — a firm's customised coordinates are
 * preserved across restarts.  Only genuinely new stockId entries are inserted.
 *
 * To force a re-seed of a specific form, delete its document from MongoDB
 * (matched by stockId) and restart the service.
 */
import { Injectable, OnApplicationBootstrap, Logger } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { FormTemplate, FormTemplateDocument } from '../common/schemas'
import { STOCK_FORMS, StockFormDefinition } from './stock-library'

/**
 * Seeds FormTemplate schema records from stock-library.ts on startup.
 * This is pure database metadata — it does NOT trigger PDF retrieval.
 *
 * PDF retrieval is the RAG Agent's job, triggered through the hierarchy:
 *   Prompt Analyst → Case/Situation Analyst → RAG Agent
 *
 * Calibration runs after PDFs are downloaded (wired inside RagAgentService).
 */
@Injectable()
export class FormLibrarySeeder implements OnApplicationBootstrap {
  private readonly logger = new Logger(FormLibrarySeeder.name)

  constructor(
    @InjectModel(FormTemplate.name) private templateModel: Model<FormTemplateDocument>,
  ) {}

  async onApplicationBootstrap() {
    try {
      const { inserted, skipped } = await this.seed()
      this.logger.log(`Form library: ${inserted} seeded, ${skipped} already present`)
    } catch (err) {
      this.logger.error('FormLibrarySeeder failed', err)
    }
  }

  async seed(): Promise<{ inserted: number; skipped: number }> {
    // Get all stockIds already present in DB
    const existing = await this.templateModel
      .find({ stockId: { $exists: true, $ne: null } })
      .select('stockId')
      .lean()
    const existingIds = new Set(existing.map((d: any) => d.stockId))

    const toInsert = STOCK_FORMS.filter(f => !existingIds.has(f.stockId))
    const skipped  = STOCK_FORMS.length - toInsert.length

    if (toInsert.length === 0) {
      this.logger.log(`Form library: all ${STOCK_FORMS.length} stock forms already seeded`)
      return { inserted: 0, skipped }
    }

    const docs = toInsert.map((f: StockFormDefinition) => ({
      stockId:          f.stockId,
      name:             f.name,
      description:      `${f.description}${f.notes ? `\n\nNote: ${f.notes}` : ''}`,
      practiceArea:     f.practiceArea,
      sourceUrl:        f.sourceUrl,
      storageKey:       '',           // populated on first generate
      fillMode:         f.fillMode,
      fields:           f.fields,
      isActive:         true,
      isSystem:         true,
      needsCalibration: f.needsCalibration,
      createdBy:        'system',
    }))

    await this.templateModel.insertMany(docs, { ordered: false })
    this.logger.log(`Form library: seeded ${toInsert.length} new stock forms (${skipped} already present)`)
    return { inserted: toInsert.length, skipped }
  }
}
