/**
 * Approval Callback API — receives approval responses from Teams/Telegram/ntfy.
 * GET or POST /api/pipelines/approval/:id?response=Approve
 */

import { NextRequest, NextResponse } from 'next/server';
import { postgresClient } from '@/lib/services/postgres-client';
import '@/lib/services/pipeline-steps';
import { pipelineEngine } from '@/lib/services/pipeline-engine';

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  return handleApproval(request, await params);
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  return handleApproval(request, await params);
}

async function handleApproval(request: NextRequest, params: { id: string }) {
  try {
    const approvalId = Number(params.id);
    const response = request.nextUrl.searchParams.get('response') || 'Approve';
    const respondedBy = request.nextUrl.searchParams.get('by') || request.headers.get('x-responded-by') || 'unknown';

    // Load approval request
    const result = await postgresClient.query(
      `SELECT * FROM approval_requests WHERE id = $1`, [approvalId]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Approval request not found' }, { status: 404 });
    }

    const approval = result.rows[0];

    if (approval.status !== 'pending') {
      return NextResponse.json({
        error: `Approval already ${approval.status}`,
        responded_by: approval.responded_by,
        responded_at: approval.responded_at,
      }, { status: 409 });
    }

    // Check expiry
    if (approval.expires_at && new Date(approval.expires_at) < new Date()) {
      await postgresClient.query(
        `UPDATE approval_requests SET status = 'timeout' WHERE id = $1`, [approvalId]
      );
      return NextResponse.json({ error: 'Approval has expired' }, { status: 410 });
    }

    // Update approval
    const status = response.toLowerCase() === 'reject' || response.toLowerCase() === 'rejected'
      ? 'rejected' : 'approved';

    await postgresClient.query(
      `UPDATE approval_requests
       SET status = $1, responded_by = $2, responded_at = NOW(), response_data = $3
       WHERE id = $4`,
      [status, respondedBy, JSON.stringify({ response, responded_by: respondedBy }), approvalId]
    );

    console.log(`[APPROVAL] #${approvalId} ${status} by ${respondedBy} (response: ${response})`);

    // Resume the pipeline execution
    try {
      await pipelineEngine.resumeExecution(approval.execution_id, {
        approval_id: approvalId,
        status,
        response,
        responded_by: respondedBy,
      });
    } catch (err) {
      console.error(`[APPROVAL] Failed to resume execution #${approval.execution_id}:`, err);
    }

    // Return a simple HTML page for browser-based approvals (Teams Action.OpenUrl)
    const html = `<!DOCTYPE html><html><body style="font-family:sans-serif;text-align:center;padding:40px">
      <h2>Approval ${status === 'approved' ? 'Accepted' : 'Rejected'}</h2>
      <p>Response: <strong>${response}</strong></p>
      <p>By: ${respondedBy}</p>
      <p style="color:#888">You can close this window.</p>
    </body></html>`;

    return new NextResponse(html, {
      headers: { 'Content-Type': 'text/html' },
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
