<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    /**
     * Generate a collision-safe filename using the authenticated user's name,
     * a compact timestamp with millisecond precision, and the original extension.
     *
     * Format: {username}_{YYYYMMDD}_{HHmmss}_{ms}.{ext}
     * Example: ghassanyusuf_20260301_120102_020.mp4
     */
    protected static function generateFilename(string $extension, ?string $username = null): string
    {
        $user = $username ?? (auth()->user()?->name ?? 'user');

        // Sanitize: lowercase, keep only alphanumeric, collapse to max 20 chars
        $slug = preg_replace('/[^a-z0-9]/', '', strtolower($user));
        $slug = substr($slug ?: 'user', 0, 20);

        $now = now();
        $ms  = str_pad((int) ($now->microsecond / 1000), 3, '0', STR_PAD_LEFT);

        $timestamp = $now->format('Ymd') . '_' . $now->format('His') . '_' . $ms;

        $ext = ltrim(strtolower($extension), '.');

        return "{$slug}_{$timestamp}.{$ext}";
    }
}
