<?php

namespace WMS\Controllers;

use WMS\Core\Request;
use WMS\Core\Response;
use WMS\Middleware\AuthMiddleware;
use WMS\Services\AuditService;
use WMS\Services\BackupService;

/**
 * BackupController - Respaldo manual del sistema y la base de datos (admin only).
 *
 * Gating: admin (ver config/role_policy.php).
 * Rutas:
 *   GET    /api/backups          -> lista de respaldos existentes
 *   POST   /api/backups          -> genera respaldo { type: 'all'|'db'|'system' }
 *   GET    /api/backups/{name}   -> descarga un respaldo
 *   DELETE /api/backups/{name}   -> elimina un respaldo
 */
class BackupController
{
    /** GET /api/backups */
    public static function index(array $params): void
    {
        try {
            $list = BackupService::listBackups();
            Response::success([
                'backups' => $list,
                'count'   => count($list),
            ], 'OK');
        } catch (\Throwable $e) {
            Response::error('Error al listar respaldos: ' . $e->getMessage(), 500);
        }
    }

    /** POST /api/backups  body: { type: 'all'|'db'|'system' } */
    public static function create(array $params): void
    {
        $body = Request::body();
        $type = strtolower((string) ($body['type'] ?? 'all'));
        if (!in_array($type, ['all', 'db', 'system'], true)) {
            Response::error('Tipo de respaldo invalido (use all|db|system)', 422);
            return;
        }

        $created = [];
        try {
            if ($type === 'db' || $type === 'all') {
                $created[] = BackupService::createDatabaseBackup();
            }
            if ($type === 'system' || $type === 'all') {
                $created[] = BackupService::createSystemBackup();
            }
        } catch (\Throwable $e) {
            Response::error('Error al generar respaldo: ' . $e->getMessage(), 500);
            return;
        }

        AuditService::logEvent('backups', 'MANUAL_BACKUP', 0, [
            'type'  => $type,
            'files' => array_column($created, 'name'),
            'user'  => AuthMiddleware::user()['username'] ?? null,
        ]);

        Response::success([
            'created' => $created,
        ], 'Respaldo generado correctamente');
    }

    /** GET /api/backups/{name} */
    public static function download(array $params): void
    {
        $name = (string) ($params['name'] ?? '');
        $path = BackupService::resolvePath($name);
        if ($path === null) {
            Response::error('Respaldo no encontrado', 404);
            return;
        }

        $mime = str_ends_with($path, '.sql') ? 'application/sql' : 'application/gzip';
        header('Content-Type: ' . $mime);
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Length: ' . filesize($path));
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');
        readfile($path);
    }

    /** DELETE /api/backups/{name} */
    public static function delete(array $params): void
    {
        $name = (string) ($params['name'] ?? '');
        $path = BackupService::resolvePath($name);
        if ($path === null) {
            Response::error('Respaldo no encontrado', 404);
            return;
        }
        if (!@unlink($path)) {
            Response::error('No se pudo eliminar el respaldo (permisos)', 500);
            return;
        }

        AuditService::logEvent('backups', 'DELETE_BACKUP', 0, [
            'file' => basename($path),
            'user' => AuthMiddleware::user()['username'] ?? null,
        ]);

        Response::success(null, 'Respaldo eliminado');
    }
}
