#!/usr/bin/env bun
/**
 * Deploy persistent resources for verification
 * Skips health check and rollback - leaves resources in Dokploy
 */

import { createProductionDokployClient } from './api/dokploy-production.js';

const STACK_NAME = `verify-${Date.now()}`;
const DOCKER_IMAGE = 'nginx:alpine';
const DOMAIN_SUFFIX = 'ai.flexinit.nl';

console.log('═══════════════════════════════════════');
console.log('  PERSISTENT DEPLOYMENT TEST');
console.log('═══════════════════════════════════════\n');

async function main() {
  const client = createProductionDokployClient();
  const projectName = `ai-stack-${STACK_NAME}`;

  console.log(`Deploying: ${STACK_NAME}`);
  console.log(`Project: ${projectName}`);
  console.log(`URL: https://${STACK_NAME}.${DOMAIN_SUFFIX}\n`);

  // Phase 1: Create Project
  console.log('[1/6] Creating project...');
  const { project, environment } = await client.createProject(
    projectName,
    `Verification deployment for ${STACK_NAME}`
  );
  console.log(`✅ Project: ${project.projectId}`);
  console.log(`✅ Environment: ${environment.environmentId}\n`);

  // Phase 2: Create Application
  console.log('[2/6] Creating application...');
  const application = await client.createApplication(
    `opencode-${STACK_NAME}`,
    environment.environmentId
  );
  console.log(`✅ Application: ${application.applicationId}\n`);

  // Phase 3: Configure Docker Image
  console.log('[3/6] Configuring Docker image...');
  await client.updateApplication(application.applicationId, {
    dockerImage: DOCKER_IMAGE,
    sourceType: 'docker',
  });
  console.log(`✅ Configured: ${DOCKER_IMAGE}\n`);

  // Phase 4: Create Domain
  console.log('[4/6] Creating domain...');
  const domain = await client.createDomain(
    `${STACK_NAME}.${DOMAIN_SUFFIX}`,
    application.applicationId,
    true,
    80
  );
  console.log(`✅ Domain: ${domain.domainId}`);
  console.log(`✅ Host: ${domain.host}\n`);

  // Phase 5: Trigger Deployment
  console.log('[5/6] Triggering deployment...');
  await client.deployApplication(application.applicationId);
  console.log(`✅ Deployment triggered\n`);

  // Phase 6: Summary
  console.log('[6/6] Deployment complete!\n');

  console.log('═══════════════════════════════════════');
  console.log('  DEPLOYMENT SUCCESSFUL');
  console.log('═══════════════════════════════════════\n');

  console.log(`📦 Resources:`);
  console.log(`  Project ID:     ${project.projectId}`);
  console.log(`  Environment ID: ${environment.environmentId}`);
  console.log(`  Application ID: ${application.applicationId}`);
  console.log(`  Domain ID:      ${domain.domainId}`);

  console.log(`\n🌐 URLs:`);
  console.log(`  Application: https://${STACK_NAME}.${DOMAIN_SUFFIX}`);
  console.log(`  Dokploy UI:  https://app.flexinit.nl/project/${project.projectId}`);

  console.log(`\n⏱️  Note: Application will be accessible in 1-2 minutes (SSL provisioning)`);

  console.log(`\n🧹 Cleanup command:`);
  console.log(`  source .env && curl -X POST -H "x-api-key: \${DOKPLOY_API_TOKEN}" \\`);
  console.log(`    https://app.flexinit.nl/api/application.delete \\`);
  console.log(`    -H "Content-Type: application/json" \\`);
  console.log(`    -d '{"applicationId":"${application.applicationId}"}'`);

  console.log('\n');

  // Output machine-readable format for verification
  const output = {
    success: true,
    stackName: STACK_NAME,
    resources: {
      projectId: project.projectId,
      environmentId: environment.environmentId,
      applicationId: application.applicationId,
      domainId: domain.domainId,
    },
    url: `https://${STACK_NAME}.${DOMAIN_SUFFIX}`,
    dokployUrl: `https://app.flexinit.nl/project/${project.projectId}`,
  };

  console.log('JSON OUTPUT:');
  console.log(JSON.stringify(output, null, 2));

  process.exit(0);
}

main().catch(error => {
  console.error('\n❌ Deployment failed:', error);
  process.exit(1);
});
