#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
COMPOSE_FILE="$ROOT/docker-compose.yml"

docker compose -f "$COMPOSE_FILE" exec -T \
  -e PLATFORM_INTERNAL_BASE_URL="${PLATFORM_INTERNAL_BASE_URL:-http://platform-service:4003/api}" \
  -e PUBLIC_BLOB_BASE_URL="${PUBLIC_BLOB_BASE_URL:-http://localhost:10000/devstoreaccount1}" \
  -e INTERNAL_BLOB_BASE_URL="${INTERNAL_BLOB_BASE_URL:-http://azurite:10000/devstoreaccount1}" \
  platform-service node --input-type=module <<'NODE'
import { createAccessToken } from './dist/modules/auth/jwt.js';

const baseUrl = process.env.PLATFORM_INTERNAL_BASE_URL;
const publicBlobBaseUrl = process.env.PUBLIC_BLOB_BASE_URL;
const internalBlobBaseUrl = process.env.INTERNAL_BLOB_BASE_URL;

const token = await createAccessToken({
  sub: 'prototype-self-test',
  email: 'self-test@bytelyst.local',
  role: 'admin',
  productId: 'lysnrai',
});

const authHeaders = {
  Authorization: `Bearer ${token}`,
};

async function request(path, init = {}) {
  const response = await fetch(`${baseUrl}${path}`, {
    ...init,
    headers: {
      ...authHeaders,
      ...(init.headers ?? {}),
    },
  });

  const text = await response.text();
  if (!response.ok) {
    throw new Error(`${path} failed with ${response.status}: ${text}`);
  }

  return text ? JSON.parse(text) : null;
}

const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const blobName = `lysnrai/prototype-self-test/${stamp}.txt`;
const payload = `prototype self-test ${stamp}`;

console.log('Checking dependency health...');
console.log(JSON.stringify(await request('/health/dependencies', { headers: {} }), null, 2));

console.log('Running platform self-test...');
console.log(JSON.stringify(await request('/self-test.json', { headers: {} }), null, 2));

console.log('Fetching blob container metadata...');
console.log(JSON.stringify(await request('/blob/containers'), null, 2));

console.log(`Requesting SAS URL for ${blobName} ...`);
const sasResponse = await request('/blob/sas', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
  },
  body: JSON.stringify({
    container: 'attachments',
    blobName,
    permissions: 'rw',
    expiresInMinutes: 10,
  }),
});

const uploadUrl = sasResponse.sasUrl.replace(publicBlobBaseUrl, internalBlobBaseUrl);
const uploadResponse = await fetch(uploadUrl, {
  method: 'PUT',
  headers: {
    'x-ms-blob-type': 'BlockBlob',
    'Content-Type': 'text/plain',
  },
  body: payload,
});

if (!uploadResponse.ok) {
  throw new Error(`SAS upload failed with ${uploadResponse.status}: ${await uploadResponse.text()}`);
}

console.log('Listing uploaded blob...');
console.log(
  JSON.stringify(
    await request(`/blob/list?container=attachments&prefix=${encodeURIComponent('lysnrai/prototype-self-test')}&limit=20`),
    null,
    2
  )
);

console.log('Fetching blob info...');
console.log(
  JSON.stringify(
    await request(`/blob/info?container=attachments&blobName=${encodeURIComponent(blobName)}`),
    null,
    2
  )
);

console.log('Deleting uploaded blob via API...');
console.log(
  JSON.stringify(
    await request('/blob/delete', {
      method: 'DELETE',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        container: 'attachments',
        blobName,
      }),
    }),
    null,
    2
  )
);

console.log('Prototype self-test finished successfully.');
NODE
