import { Injectable, Logger } from "@nestjs/common";
import { DataSource } from "typeorm";

import { FileUploadField } from "../modules/file-upload-settings/entities/file-upload-field.entity";
import { FileUploadSetting } from "../modules/file-upload-settings/entities/file-upload-setting.entity";

const COMPANY_ONBOARDING_DOCUMENTS = [
  {
    code: "company_onboarding_documents_customer",
    label: "Customer onboarding documents",
    entity: "customer",
  },
  {
    code: "company_onboarding_documents_forwarder",
    label: "Forwarder onboarding documents",
    entity: "other",
  },
  {
    code: "company_onboarding_documents_transporter",
    label: "Transporter onboarding documents",
    entity: "other",
  },
  {
    code: "company_onboarding_documents_forwarder_dj",
    label: "Djibouti forwarder onboarding documents",
    entity: "other",
  },
] as const;

const COMPANY_ONBOARDING_DESCRIPTION =
  "Required documents for external company onboarding. The same set applies to customers, forwarders, transporters, and brokers.";

const COMPANY_ONBOARDING_FIELDS = [
  {
    fileKey: "business_license",
    fileLabel: "Business License / Trade License",
    helpText: "Verified against the government trade system during registration.",
    isRequired: true,
    isMultiple: false,
    maxFiles: 1,
    allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
    maxSizeMb: 10,
    displayOrder: 1,
  },
  {
    fileKey: "tin_certificate",
    fileLabel: "TIN Certificate",
    helpText: "Verified against the TIN registry during registration.",
    isRequired: true,
    isMultiple: false,
    maxFiles: 1,
    allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
    maxSizeMb: 10,
    displayOrder: 2,
  },
  {
    fileKey: "national_id_passport",
    fileLabel: "National ID / Passport",
    helpText: "Verified against the National ID API during registration.",
    isRequired: true,
    isMultiple: false,
    maxFiles: 1,
    allowedExtensions: ["pdf", "jpg", "jpeg", "png"],
    maxSizeMb: 10,
    displayOrder: 3,
  },
] as const;

@Injectable()
export class FileUploadSettingsSeeder {
  private readonly logger = new Logger(FileUploadSettingsSeeder.name);

  constructor(private readonly dataSource: DataSource) {}

  async run() {
    await this.dataSource.transaction(async (manager) => {
      const settingRepository = manager.getRepository(FileUploadSetting);
      const fieldRepository = manager.getRepository(FileUploadField);

      for (const documentSetting of COMPANY_ONBOARDING_DOCUMENTS) {
        await settingRepository.upsert(
          {
            code: documentSetting.code,
            label: documentSetting.label,
            description: COMPANY_ONBOARDING_DESCRIPTION,
            entity: documentSetting.entity,
          },
          {
            conflictPaths: { code: true },
          },
        );

        const setting = await settingRepository.findOne({
          where: { code: documentSetting.code },
          select: { id: true, code: true },
        });

        if (!setting) {
          throw new Error(`file_upload_setting_seed_failed:${documentSetting.code}`);
        }

        await fieldRepository.delete({ settingId: setting.id });

        await fieldRepository.insert(
          COMPANY_ONBOARDING_FIELDS.map((field, index) => ({
            settingId: setting.id,
            fileKey: field.fileKey,
            fileLabel: field.fileLabel,
            helpText: field.helpText,
            isRequired: field.isRequired,
            isMultiple: field.isMultiple,
            maxFiles: field.maxFiles,
            allowedExtensions: [...field.allowedExtensions],
            maxSizeMb: field.maxSizeMb,
            displayOrder: field.displayOrder ?? index + 1,
          })),
        );
      }
    });

    this.logger.log(
      "Ensured company onboarding file upload settings for external companies",
    );
  }
}
