// electron-builder `afterAllArtifactBuild` hook (H8).
//
// The in-app updater (src/main/updater.ts) sets REQUIRE_CHECKSUM = true and
// refuses any release whose installer lacks a sibling `<installer>.exe.sha256`
// asset — so a release published without one makes EVERY client's in-app update
// fail. `build:win` never generated these, so they had to be made by hand (and
// the 0.5.0 build shipped without any). This hook writes one next to every built
// `.exe`, in `sha256sum` format (`<lowercase-hex>  <filename>`), which the
// updater's extractSha256 parses (it just needs a standalone 64-char hex token).
//
// Returning the paths tells electron-builder to also upload them as release
// assets when publishing.

const { createHash } = require('crypto')
const { readFileSync, writeFileSync } = require('fs')
const { basename } = require('path')

/** The `sha256sum`-format line for a file: "<lowercase-hex>  <basename>". */
function checksumLine(filePath) {
  const hex = createHash('sha256').update(readFileSync(filePath)).digest('hex')
  return `${hex}  ${basename(filePath)}`
}

exports.default = function generateChecksums(context) {
  const written = []
  for (const file of context.artifactPaths) {
    if (!/\.exe$/i.test(file)) continue
    const out = `${file}.sha256`
    writeFileSync(out, checksumLine(file) + '\n')
    written.push(out)
  }
  return written
}

// Exported for unit testing the hashing/format without running electron-builder.
exports.checksumLine = checksumLine
