<?php

namespace Modules\APIPublica\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Tenant\ConnectionManager;
use Modules\APIPublica\Services\WebhookService;
use PDO;

class WebhooksController {
    public function list(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            
            $stmt = $pdo->prepare('SELECT * FROM webhooks WHERE tenant_id = ? ORDER BY created_at DESC');
            $stmt->execute([$tenantId]);
            $webhooks = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return Response::json(['data' => $webhooks]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function create(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $body = is_array($req->body) ? $req->body : [];

            $stmt = $pdo->prepare('
                INSERT INTO webhooks (
                    tenant_id, nome, url, eventos_json, metodo_http,
                    headers_json, secret, ativo, max_tentativas, intervalo_retry_segundos
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ');
            $stmt->execute([
                $tenantId,
                $body['nome'],
                $body['url'],
                json_encode($body['eventos'] ?? []),
                $body['metodo_http'] ?? 'POST',
                !empty($body['headers']) ? json_encode($body['headers']) : null,
                $body['secret'] ?? null,
                $body['ativo'] ?? true,
                $body['max_tentativas'] ?? 3,
                $body['intervalo_retry_segundos'] ?? 60
            ]);

            $webhookId = (int)$pdo->lastInsertId();

            return Response::json(['data' => ['id' => $webhookId]], 201);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function update(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $id = (int)($req->get('params')[0] ?? 0);
            $body = is_array($req->body) ? $req->body : [];

            $allowedFields = ['nome', 'url', 'eventos', 'metodo_http', 'headers', 'secret', 'ativo', 'max_tentativas', 'intervalo_retry_segundos'];
            $updates = [];
            $params = [];

            foreach ($allowedFields as $field) {
                if (isset($body[$field])) {
                    if ($field === 'eventos' || $field === 'headers') {
                        $updates[] = ($field === 'eventos' ? 'eventos_json' : 'headers_json') . " = ?";
                        $params[] = json_encode($body[$field]);
                    } else {
                        $updates[] = "{$field} = ?";
                        $params[] = $body[$field];
                    }
                }
            }

            if (empty($updates)) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'Nenhum campo para atualizar']]);
            }

            $params[] = $id;
            $params[] = $tenantId;

            $sql = 'UPDATE webhooks SET ' . implode(', ', $updates) . ' WHERE id = ? AND tenant_id = ?';
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);

            return Response::json(['data' => ['success' => true]]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function delete(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $id = (int)($req->get('params')[0] ?? 0);

            $stmt = $pdo->prepare('DELETE FROM webhooks WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$id, $tenantId]);

            if ($stmt->rowCount() === 0) {
                return new Response(404, ['error' => ['code' => 'not_found', 'message' => 'Webhook não encontrado']]);
            }

            return Response::json(['data' => ['success' => true]]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function test(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = ConnectionManager::forTenant();
            $id = (int)($req->get('params')[0] ?? 0);

            $stmt = $pdo->prepare('SELECT * FROM webhooks WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$id, $tenantId]);
            $webhook = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$webhook) {
                return new Response(404, ['error' => ['code' => 'not_found', 'message' => 'Webhook não encontrado']]);
            }

            // Disparar webhook de teste
            $webhookService = new WebhookService($tenantId);
            $webhookService->disparar('test', ['test' => true, 'webhook_id' => $id]);

            return Response::json(['data' => ['success' => true, 'message' => 'Webhook de teste disparado']]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }
}

