<?php

namespace Modules\Integracoes\Instagram\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\Integracoes\Instagram\Services\InstagramAPIService;

class InstagramController {
    public function getConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $service = new InstagramAPIService($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 InstagramAPIService($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 InstagramAPIService($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 ip.*, p.codigo, p.nome, p.preco
                FROM instagram_produtos ip
                INNER JOIN products p ON ip.product_id = p.id
                WHERE ip.tenant_id = ?
                ORDER BY ip.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 InstagramAPIService($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 instagram_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 InstagramAPIService($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 getEstatisticas(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $mediaId = $req->query['media_id'] ?? null;
            
            if (!$mediaId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'media_id é obrigatório']]);
            }

            $service = new InstagramAPIService($tenantId);
            $estatisticas = $service->getEstatisticasPublicacao($mediaId);

            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 InstagramAPIService($tenantId);
            $service->processarWebhook($body, $headers);

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

