<?php

namespace Modules\Integracoes\OpenBanking\Controllers;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Modules\Integracoes\OpenBanking\Services\OpenBankingAPIService;

class OpenBankingController {
    public function dashboard(Request $req): Response {
        return new Response(200, [], '<h1>Open Banking</h1><p>Interface em desenvolvimento...</p>');
    }

    public function getConfig(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $bancoCodigo = $req->query['banco_codigo'] ?? null;

            $service = new OpenBankingAPIService($tenantId);
            $config = $service->getConfig($bancoCodigo);

            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 : [];
            $bancoCodigo = $body['banco_codigo'] ?? '';

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

            $service = new OpenBankingAPIService($tenantId);
            $service->updateConfig($bancoCodigo, $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;
            $state = $req->query['state'] ?? null;
            $bancoCodigo = $req->query['banco_codigo'] ?? null;

            if (!$code) {
                return new Response(400, ['error' => ['code' => 'missing_code', 'message' => 'Código de autorização não fornecido']]);
            }

            if (!$bancoCodigo) {
                return new Response(400, ['error' => ['code' => 'missing_banco', 'message' => 'Código do banco não fornecido']]);
            }

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

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

    public function listContas(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $bancoCodigo = $req->query['banco_codigo'] ?? null;

            $service = new OpenBankingAPIService($tenantId);
            $contas = $service->listContas($bancoCodigo);

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

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

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

            $service = new OpenBankingAPIService($tenantId);
            $saldo = $service->getSaldo($contaId);

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

    public function getExtrato(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $contaId = (int)($req->get('params')[0] ?? 0);
            $dataInicio = $req->query['data_inicio'] ?? null;
            $dataFim = $req->query['data_fim'] ?? null;

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

            $service = new OpenBankingAPIService($tenantId);
            $extrato = $service->getExtrato($contaId, $dataInicio, $dataFim);

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

    public function conciliacaoAutomatica(Request $req): Response {
        try {
            $tenantId = \Gestoreasy\Core\Tenant\TenantContext::getTenantId();
            $body = is_array($req->body) ? $req->body : [];
            $bancoCodigo = $body['banco_codigo'] ?? null;
            $dataInicio = $body['data_inicio'] ?? null;
            $dataFim = $body['data_fim'] ?? null;

            $service = new OpenBankingAPIService($tenantId);
            $resultado = $service->conciliacaoAutomatica($bancoCodigo, $dataInicio, $dataFim);

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

