<?php

declare(strict_types=1);

namespace App\Controllers\Api\Admin;

use CodeIgniter\HTTP\ResponseInterface;

/**
 * Utilitas: daftar file backup SQL di writable, buat backup, hapus file.
 */
class DatabaseBackupApiController extends BaseAdminApiController
{
    public function index(): ResponseInterface
    {
        $auth = $this->requireAdminApiAccess('utilitas');
        if ($auth['response'] !== null) {
            return $auth['response'];
        }
        $this->auditAuthorized('api.admin.backup.list', $auth['actor'], ['request' => $this->auditRequestParams()]);

        return $this->respond($this->adminExtra->backupListFiles());
    }

    public function run(): ResponseInterface
    {
        $auth = $this->requireAdminApiAccess('utilitas');
        if ($auth['response'] !== null) {
            return $auth['response'];
        }
        $also = (string) ($this->request->getPost('save_latest') ?? '') === '1';
        $this->auditAuthorized('api.admin.backup.run', $auth['actor'], [
            'save_latest' => $also,
            'request'     => $this->auditRequestParams(),
        ]);

        return $this->respond($this->adminExtra->backupRun($also));
    }

    public function delete(string $file): ResponseInterface
    {
        $auth = $this->requireAdminApiAccess('utilitas');
        if ($auth['response'] !== null) {
            return $auth['response'];
        }
        $this->auditAuthorized('api.admin.backup.delete', $auth['actor'], ['file' => $file]);

        return $this->respond($this->adminExtra->backupDelete($file));
    }
}
