import { readFile } from 'fs/promises';
import { resolve } from 'path';
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../src/app.module';
import { SyncService } from '../src/sync/sync.service';
import { SdsProductDetail } from '../src/sync/sds-client.service';

async function main(): Promise<void> {
  const inputPath = process.argv[2];
  if (!inputPath) {
    throw new Error('Usage: pnpm --filter @inkreach/api import:product-detail -- <product_detail.txt>');
  }
  const absolutePath = resolve(inputPath);
  const raw = await readFile(absolutePath, 'utf8');
  const jsonStart = raw.indexOf('{');
  if (jsonStart < 0) throw new Error('No JSON object found in product detail file');
  const detail = JSON.parse(raw.slice(jsonStart)) as SdsProductDetail;

  const app = await NestFactory.createApplicationContext(AppModule, { logger: ['error', 'warn'] });
  try {
    const result = await app.get(SyncService).importProductDetail(detail);
    process.stdout.write(
      `Imported SDS product ${result.goodId}: ${result.variants} variants, ` +
        `${result.sizeRows} size rows, ${result.packageRows} package rows, ` +
        `${result.configuredGoods} configured goods\n`,
    );
  } finally {
    await app.close();
  }
}

void main().catch((error: unknown) => {
  const message = error instanceof Error ? error.stack ?? error.message : String(error);
  process.stderr.write(`${message}\n`);
  process.exitCode = 1;
});
