<?php

namespace Modules\Integracoes\Facebook\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\Integracoes\Facebook\Services\FacebookAPIService;

class FacebookController {
    public function getConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $service = new FacebookAPIService($tenantId);
            $config = $service->getConfig();

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

    public function updateConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            
            $service = new FacebookAPIService($tenantId);
            $service->updateConfig($body);

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

    public function oauthCallback(Request $req): Response {
        try {
            $code = $req->query['code'] ?? null;
            $redirectUri = $req->query['redirect_uri'] ?? ($_SERVER['HTTP_REFERER'] ?? '');
            
            if (!$code) {
                return new Response(400, ['error' => ['code' => 'missing_code', 'message' => 'Código de autorização não fornecido']]);
            }

            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $service = new FacebookAPIService($tenantId);
            $result = $service->trocarCodePorToken($code, $redirectUri);

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

    public function listProdutos(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant();
            
            $stmt = $pdo->prepare('
                SELECT fp.*, p.codigo, p.nome, p.preco
                FROM facebook_produtos fp
                INNER JOIN products p ON fp.product_id = p.id
                WHERE fp.tenant_id = ?
                ORDER BY fp.updated_at DESC
            ');
            $stmt->execute([$tenantId]);
            $produtos = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

    public function sincronizarProdutos(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $service = new FacebookAPIService($tenantId);
            $resultado = $service->sincronizarProdutos();

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

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

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

    public function criarPublicacao(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            
            $service = new FacebookAPIService($tenantId);
            $resultado = $service->criarPublicacao($body);

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

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

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

    public function criarAnuncio(Request $req): Response {
        try {
            // TODO: Implementar criação de anúncio
            return Response::json(['data' => ['message' => 'Criação de anúncio em desenvolvimento']]);
        } catch (\Exception $e) {
            return new Response(500, ['error' => ['code' => 'error', 'message' => $e->getMessage()]]);
        }
    }

    public function getEstatisticas(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $postId = $req->query['post_id'] ?? null;
            
            if (!$postId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'post_id é obrigatório']]);
            }

            $service = new FacebookAPIService($tenantId);
            $estatisticas = $service->getEstatisticasPublicacao($postId);

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

    public function webhook(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            $headers = $req->headers ?? [];
            
            $service = new FacebookAPIService($tenantId);
            $service->processarWebhook($body, $headers);

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

