<?php

namespace App\Controllers;

use App\Libraries\ApiKeyManager;
use App\Models\ApiKeyModel;

class ApiKeys extends BaseController
{
    public function index()
    {
        if ($redirect = $this->requireOrganizationContext()) {
            return $redirect;
        }

        if (! $this->canManageOrganization()) {
            return redirect()->to(site_url('dashboard'))->with('error', 'Nao tens permissao para gerir API keys.');
        }

        $model = new ApiKeyModel();

        return view('api_keys/index', [
            'title' => 'API Keys',
            'active' => 'api_keys',
            'apiKeys' => $model->forOrganization((int) $this->currentOrganizationId()),
            'availableScopes' => ApiKeyManager::PUBLIC_SCOPES,
            'newApiKeyToken' => session()->getFlashdata('new_api_key_token'),
        ]);
    }

    public function create()
    {
        if ($redirect = $this->requireOrganizationContext()) {
            return $redirect;
        }

        if (! $this->canManageOrganization()) {
            return redirect()->to(site_url('dashboard'))->with('error', 'Nao tens permissao para emitir API keys.');
        }

        $payload = [
            'name' => trim((string) $this->request->getPost('name')),
            'expires_at' => trim((string) $this->request->getPost('expires_at')),
            'scopes' => $this->request->getPost('scopes') ?? [],
        ];

        $rules = [
            'name' => 'required|min_length[3]|max_length[120]',
        ];

        if (! $this->validateData($payload, $rules)) {
            return redirect()->back()
                ->withInput()
                ->with('errors', $this->validator->getErrors())
                ->with('error', 'Verifica os dados da API key.');
        }

        if ($payload['expires_at'] !== '') {
            $expiresAt = date_create($payload['expires_at']);
            if ($expiresAt === false) {
                return redirect()->back()->withInput()->with('error', 'A data de expiracao da API key e invalida.');
            }
        }

        $manager = new ApiKeyManager();
        $scopes = $manager->normalizeScopes((array) $payload['scopes']);

        if ($scopes === []) {
            return redirect()->back()->withInput()->with('error', 'Seleciona pelo menos um scope.');
        }

        $result = $manager->createKey(
            (int) $this->currentOrganizationId(),
            $payload['name'],
            $scopes,
            (int) ($this->authUser()['id'] ?? 0),
            $payload['expires_at'] !== '' ? str_replace('T', ' ', $payload['expires_at']) . ':00' : null
        );

        return redirect()->to(site_url('api-keys'))
            ->with('success', 'API key emitida com sucesso. Guarda o token agora: ele nao volta a ser mostrado.')
            ->with('new_api_key_token', $result['token']);
    }

    public function revoke(int $id)
    {
        if ($redirect = $this->requireOrganizationContext()) {
            return $redirect;
        }

        if (! $this->canManageOrganization()) {
            return redirect()->to(site_url('dashboard'))->with('error', 'Nao tens permissao para revogar API keys.');
        }

        $model = new ApiKeyModel();
        $apiKey = $model->find($id);

        if (! $apiKey || (int) $apiKey['organization_id'] !== (int) $this->currentOrganizationId()) {
            return redirect()->to(site_url('api-keys'))->with('error', 'API key nao encontrada.');
        }

        $model->update($id, ['status' => 'revoked']);

        return redirect()->to(site_url('api-keys'))->with('success', 'API key revogada com sucesso.');
    }
}
