#!/usr/bin/env node
/**
 * Seed deploy.SoftwareRelease from releases/manifest.json (data-driven catalog).
 * Usage: node scripts/seed-software-releases.js [--publish]
 */
'use strict';

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const manifestPath = path.join(__dirname, '../releases/manifest.json');
if (!fs.existsSync(manifestPath)) {
  console.error('[seed-releases] Run: node scripts/build-release-artifacts.js first');
  process.exit(1);
}

try {
  require(path.join(__dirname, '../src/api/node_modules/dotenv')).config({ path: path.join(__dirname, '../.env') });
} catch {
  /* env may already be set */
}

const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
const publish = process.argv.includes('--publish');

async function main() {
  const db = require('../src/api/db');
  let seeded = 0;

  for (const rel of manifest.releases || []) {
    const existing = await db.query(`
      SELECT ReleaseId FROM deploy.SoftwareRelease
      WHERE ProductCode = @code AND Version = @ver AND Channel = @ch
    `, { code: rel.productCode, ver: rel.version, ch: rel.channel || 'stable' });

    let releaseId = existing.recordset?.[0]?.ReleaseId;
    if (!releaseId) {
      releaseId = crypto.randomUUID();
      await db.query(`
        INSERT INTO deploy.SoftwareRelease (ReleaseId, ProductCode, Version, Channel, Title, ReleaseNotes, MinLicenseTier, IsPublished, PublishedAt, CreatedBy)
        VALUES (@id, @code, @ver, @ch, @title, @notes, @tier, @pub, CASE WHEN @pub = 1 THEN SYSUTCDATETIME() ELSE NULL END, 'seed-script')
      `, {
        id: releaseId,
        code: rel.productCode,
        ver: rel.version,
        ch: rel.channel || 'stable',
        title: rel.title,
        notes: rel.releaseNotes || null,
        tier: rel.minLicenseTier || null,
        pub: publish ? 1 : 0,
      });
    } else if (publish) {
      await db.query(`
        UPDATE deploy.SoftwareRelease SET IsPublished = 1, PublishedAt = SYSUTCDATETIME() WHERE ReleaseId = @id
      `, { id: releaseId });
    }

    for (const art of rel.artifacts || []) {
      const artifactId = crypto.randomUUID();
      await db.query(`
        MERGE deploy.SoftwareReleaseArtifact AS t
        USING (SELECT @rid AS ReleaseId, @plat AS Platform, @arch AS Architecture, @pkg AS PackageType) AS s
          ON t.ReleaseId = s.ReleaseId AND t.Platform = s.Platform AND t.Architecture = s.Architecture AND t.PackageType = s.PackageType
        WHEN MATCHED THEN UPDATE SET
          FileName = @fn, StoragePath = @sp, Sha256Hex = @sha, FileSizeBytes = @sz,
          InstallCommand = @ic, IsActive = 1, UploadedAt = SYSUTCDATETIME()
        WHEN NOT MATCHED THEN INSERT (ArtifactId, ReleaseId, Platform, Architecture, PackageType, FileName, StoragePath, Sha256Hex, FileSizeBytes, ContentType, InstallCommand, UploadedBy)
        VALUES (@aid, @rid, @plat, @arch, @pkg, @fn, @sp, @sha, @sz, @ct, @ic, 'seed-script');
      `, {
        aid: artifactId,
        rid: releaseId,
        plat: art.platform,
        arch: art.architecture,
        pkg: art.packageType,
        fn: art.fileName,
        sp: art.storagePath,
        sha: art.sha256,
        sz: art.fileSizeBytes,
        ct: art.packageType === 'zip' ? 'application/zip' : 'application/gzip',
        ic: art.installCommand || null,
      });
      seeded += 1;
    }
  }

  console.log(`[seed-releases] Seeded ${seeded} artifacts (${manifest.releases?.length || 0} products) publish=${publish}`);
  try {
    const pool = await db.getPool();
    if (pool) await pool.close();
  } catch { /* */ }
}

main().catch((e) => {
  console.error('[seed-releases]', e.message);
  process.exit(1);
});
