<?php

namespace Modules\Integracoes\TikTokSeller\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\Integracoes\TikTokSeller\Services\TikTokSellerAPIService;

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

            unset($config['access_token'], $config['refresh_token'], $config['app_secret']);

            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 TikTokSellerAPIService($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;
            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 TikTokSellerAPIService($tenantId);
            $result = $service->handleOAuthCallback($code);

            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 tp.*, p.codigo, p.nome, p.preco, p.estoque
                FROM tiktok_produtos tp
                INNER JOIN products p ON tp.product_id = p.id
                WHERE tp.tenant_id = ?
                ORDER BY tp.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 TikTokSellerAPIService($tenantId);
            $resultado = $service->sincronizarProdutos();

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

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

            if (!$productId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'product_id é obrigatório']]);
            }

            $service = new TikTokSellerAPIService($tenantId);
            $resultado = $service->publicarProduto($productId, $body);

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

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

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

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

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

    public function importarPedido(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $tiktokOrderId = $req->get('params')[0] ?? null;

            if (!$tiktokOrderId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'order_id é obrigatório']]);
            }

            $service = new TikTokSellerAPIService($tenantId);
            $resultado = $service->importarPedido($tiktokOrderId);

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

    public function sincronizarEstoque(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            $productId = (int)($body['product_id'] ?? 0);

            if (!$productId) {
                return new Response(422, ['error' => ['code' => 'validation_error', 'message' => 'product_id é obrigatório']]);
            }

            $service = new TikTokSellerAPIService($tenantId);
            $resultado = $service->sincronizarEstoque($productId);

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

    public function webhook(Request $req): Response {
        try {
            $body = is_array($req->body) ? $req->body : [];
            $token = $req->headers['X-Webhook-Token'] ?? $body['token'] ?? null;

            // Validar token
            $pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant();
            $stmt = $pdo->prepare('SELECT tenant_id FROM tiktok_config WHERE webhook_token = ? AND ativo = 1');
            $stmt->execute([$token]);
            $config = $stmt->fetch(\PDO::FETCH_ASSOC);

            if (!$config) {
                return new Response(401, ['error' => ['code' => 'unauthorized', 'message' => 'Token inválido']]);
            }

            $service = new TikTokSellerAPIService($config['tenant_id']);
            $service->processarWebhook($body);

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

