<?php
declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

function storage_base(array $config): string {
  return rtrim($config['storage_path'], '/');
}

function ensure_dir(string $path): void {
  if (!is_dir($path)) {
    if (!mkdir($path, 0750, true) && !is_dir($path)) {
      throw new RuntimeException("Cannot create dir: $path");
    }
  }
}

function vehicle_docs_dir(array $config, int $vehicleId): string {
  return storage_base($config) . "/vehicles/{$vehicleId}/docs";
}
function vehicle_photos_dir(array $config, int $vehicleId): string {
  return storage_base($config) . "/vehicles/{$vehicleId}/photos";
}
function vehicle_pdfs_dir(array $config, int $vehicleId): string {
  return storage_base($config) . "/vehicles/{$vehicleId}/generated_pdfs";
}

function file_sha256(string $path): string {
  return hash_file('sha256', $path);
}

function allowed_doc_mimes(): array {
  return [
    'application/pdf',
    'image/jpeg',
    'image/png',
  ];
}

function allowed_photo_mimes(): array {
  return [
    'image/jpeg',
    'image/png'
  ];
}

function safe_store_upload(array $file, string $targetDir, array $allowedMime, int $maxBytes): array {
  if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    throw new RuntimeException("Upload error.");
  }
  $tmp = $file['tmp_name'];
  $original = basename((string)$file['name']);
  $size = (int)$file['size'];
  if ($size <= 0 || $size > $maxBytes) {
    throw new RuntimeException("Invalid file size.");
  }

  $finfo = new finfo(FILEINFO_MIME_TYPE);
  $mime = $finfo->file($tmp) ?: 'application/octet-stream';
  if (!in_array($mime, $allowedMime, true)) {
    throw new RuntimeException("File type not allowed: {$mime}");
  }

  ensure_dir($targetDir);

  $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
  $stored = bin2hex(random_bytes(16)) . ($ext ? ".{$ext}" : "");
  $dest = rtrim($targetDir, '/') . '/' . $stored;

  if (!move_uploaded_file($tmp, $dest)) {
    throw new RuntimeException("Failed to move upload.");
  }

  return [
    'original_filename' => $original,
    'stored_filename' => $stored,
    'mime_type' => $mime,
    'file_size' => $size,
    'sha256' => file_sha256($dest),
    'abs_path' => $dest
  ];
}
