<?php

namespace App\Controllers;

use App\Services\Storage\FileStorageException;
use App\Services\StorageBrowserService;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;

class StorageBrowserController extends BaseController
{
    use ResponseTrait;
    private StorageBrowserService $browser;

    public function __construct()
    {
        $this->browser = new StorageBrowserService();
    }

    public function index(): string
    {
        return view('storage/file_browser', [
            'driver' => $this->browser->driverLabel(),
            'bucket' => $this->browser->bucketLabel(),
        ]);
    }

    public function folders(): ResponseInterface
    {
        return $this->respond([
            'status'  => 'success',
            'driver'  => $this->browser->driverLabel(),
            'bucket'  => $this->browser->bucketLabel(),
            'folders' => $this->browser->folders(),
        ]);
    }

    public function files(): ResponseInterface
    {
        try {
            $folder = (string) ($this->request->getGet('folder') ?? '');
            $search = $this->request->getGet('q');
            $token  = $this->request->getGet('page_token');
            $limit  = max(1, min(50, (int) ($this->request->getGet('limit') ?? 10)));

            if ($folder === '') {
                return $this->respond([
                    'status'  => 'success',
                    'driver'  => $this->browser->driverLabel(),
                    'bucket'  => $this->browser->bucketLabel(),
                    'folder'  => '',
                    'files'   => [],
                    'has_more' => false,
                    'next_token' => null,
                ]);
            }

            $result = $this->browser->listFiles(
                $folder,
                $limit,
                is_string($token) && $token !== '' ? $token : null,
                is_string($search) ? $search : null
            );

            return $this->respond([
                'status'     => 'success',
                'driver'     => $this->browser->driverLabel(),
                'bucket'     => $this->browser->bucketLabel(),
                'folder'     => $folder,
                'files'      => $result['files'],
                'has_more'   => $result['has_more'],
                'next_token' => $result['next_token'],
            ]);
        } catch (FileStorageException $e) {
            return $this->respond([
                'status'  => 'failed',
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function open()
    {
        try {
            $key = (string) ($this->request->getGet('key') ?? '');

            return redirect()->to($this->browser->getOpenUrl($key));
        } catch (FileStorageException $e) {
            return $this->respond([
                'status'  => 'failed',
                'message' => $e->getMessage(),
            ], 404);
        }
    }

    public function download()
    {
        try {
            $key = (string) ($this->request->getGet('key') ?? '');

            return $this->browser->downloadResponse($key);
        } catch (FileStorageException $e) {
            return $this->respond([
                'status'  => 'failed',
                'message' => $e->getMessage(),
            ], 404);
        }
    }
}
