import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { WorkflowTemplate, WorkflowTemplateDocument } from '../common/schemas'
import { STOCK_WORKFLOWS } from './workflow-library'

@Injectable()
export class WorkflowLibrarySeeder implements OnApplicationBootstrap {
  private readonly logger = new Logger(WorkflowLibrarySeeder.name)

  constructor(
    @InjectModel(WorkflowTemplate.name)
    private readonly templateModel: Model<WorkflowTemplateDocument>,
  ) {}

  async onApplicationBootstrap() {
    let seeded = 0, skipped = 0
    for (const wf of STOCK_WORKFLOWS) {
      const exists = await this.templateModel.exists({ stockId: wf.stockId })
      if (exists) { skipped++; continue }
      await this.templateModel.create({
        ...wf,
        isActive: true,
        createdBy: 'system',
      })
      seeded++
    }
    this.logger.log(`Workflow library: ${seeded} seeded, ${skipped} already present`)
  }
}
