import type { FastifyInstance } from 'fastify';
import pino from 'pino';
import crypto from 'node:crypto';
import { config } from '../config/index.js';

const logger = pino({ name: 'slackbot' });

/**
 * Slack interactive message handler.
 * Receives button clicks for approve/reject from Slack Block Kit messages.
 */
export function registerSlackRoutes(app: FastifyInstance) {
  // Slack Events API verification + interactive payloads
  app.post('/slack/events', async (req, reply) => {
    // Verify Slack signature
    if (config.SLACK_SIGNING_SECRET) {
      const timestamp = req.headers['x-slack-request-timestamp'] as string;
      const signature = req.headers['x-slack-signature'] as string;
      const body = JSON.stringify(req.body);

      if (!verifySlackSignature(body, timestamp, signature, config.SLACK_SIGNING_SECRET)) {
        return reply.status(401).send({ error: 'Invalid signature' });
      }
    }

    const payload = req.body as any;

    // URL verification challenge
    if (payload.type === 'url_verification') {
      return { challenge: payload.challenge };
    }

    return { ok: true };
  });

  // Slack interactive components (button clicks)
  app.post('/slack/interactions', async (req, reply) => {
    // Slack sends form-encoded payload
    const rawPayload = (req.body as any)?.payload;
    if (!rawPayload) return reply.status(400).send({ error: 'Missing payload' });

    let payload: any;
    try {
      payload = JSON.parse(rawPayload);
    } catch {
      return reply.status(400).send({ error: 'Invalid payload' });
    }

    if (payload.type === 'block_actions') {
      for (const action of payload.actions ?? []) {
        const [actionType, stepId] = (action.action_id ?? '').split(':');

        if (actionType === 'approve_step') {
          logger.info({ stepId, user: payload.user?.id }, 'Step approved via Slack');
          // TODO: Update audit entry, resume execution
        } else if (actionType === 'reject_step') {
          logger.info({ stepId, user: payload.user?.id }, 'Step rejected via Slack');
          // TODO: Update audit entry, abort execution
        }
      }
    }

    return { ok: true };
  });
}

function verifySlackSignature(body: string, timestamp: string, signature: string, secret: string): boolean {
  if (!timestamp || !signature) return false;

  // Reject stale requests (>5 min)
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - parseInt(timestamp, 10)) > 300) return false;

  const sigBasestring = `v0:${timestamp}:${body}`;
  const expected = 'v0=' + crypto.createHmac('sha256', secret).update(sigBasestring).digest('hex');

  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
