<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Services\BackupService;

class BackupController extends BaseController
{
    private BackupService $backupService;

    public function __construct($request)
    {
        parent::__construct($request);
        $this->backupService = new BackupService();
    }

    public function index(): void
    {
        $page = (int) ($this->request->query('page', 1));
        $perPage = (int) ($this->request->query('per_page', 20));

        $result = $this->backupService->getBackups($page, $perPage);

        Response::paginated($result['items'], $result['total'], $result['page'], $result['per_page'], 'Backups consultados correctamente');
    }

    public function store(): void
    {
        try {
            $backup = $this->backupService->createBackup($this->getAuthUserId());
            Response::created($backup, 'Backup creado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 500);
        }
    }

    public function download(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $backup = $this->backupService->downloadBackup($id);
            Response::download($backup['file_path'], $backup['file_name'], 'application/sql');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 400);
        }
    }

    public function restore(): void
    {
        $id = (int) $this->getRouteParam('id');

        try {
            $this->backupService->restoreBackup($id);
            Response::success(null, 'Backup restaurado correctamente');
        } catch (\RuntimeException $e) {
            Response::error($e->getMessage(), $e->getCode() ?: 500);
        }
    }
}
