<?php
// app/services/PathTool.php

declare(strict_types=1);

namespace ScMedia\Services;

final class PathTool {
  public function testPath(string $path, array $checks): array {
    $res = [
      'exists' => null,
      'read' => null,
      'write' => null,
      'rename' => null,
    ];

    $notes = [];

    $path = rtrim($path, "/");
    if ($path === '') {
      return [
        'results' => $res,
        'notes' => ['Empty path'],
      ];
    }

    if (in_array('exists', $checks, true)) {
      $res['exists'] = file_exists($path);
      if (!$res['exists']) {
        $notes[] = "Path does not exist";
      }
    }

    if (in_array('read', $checks, true)) {
      $res['read'] = is_readable($path);
      if (!$res['read']) {
        $notes[] = "Not readable";
      }
    }

    if (in_array('write', $checks, true)) {
      $res['write'] = is_writable($path);
      if (!$res['write']) {
        $notes[] = "Not writable";
      }
    }

    if (in_array('rename', $checks, true)) {
      // Rename test: create temp file and rename it in same directory
      $dir = $path;
      if (!is_dir($dir)) {
        $dir = dirname($path);
      }
      $tmp1 = $dir . "/.scmedia_test_" . bin2hex(random_bytes(6));
      $tmp2 = $tmp1 . "_renamed";

      $ok = false;
      try {
        $created = @file_put_contents($tmp1, "test");
        if ($created === false) {
          $notes[] = "Rename test: cannot create temp file";
        } else {
          $ren = @rename($tmp1, $tmp2);
          if ($ren) {
            $ok = true;
            @unlink($tmp2);
          } else {
            $notes[] = "Rename test: rename() failed";
            @unlink($tmp1);
          }
        }
      } catch (\Throwable $e) {
        $notes[] = "Rename test exception: " . $e->getMessage();
        @unlink($tmp1);
        @unlink($tmp2);
      }
      $res['rename'] = $ok;
    }

    return [
      'results' => $res,
      'notes' => $notes,
    ];
  }
}
