<?php

namespace App\Services\Interview;

use CodeIgniter\HTTP\Files\UploadedFile;

/**
 * Files attached to an interview — assessment documents, signed offers,
 * scanned notes, screenshots. Broader allow-list than resumes, but same
 * security pattern: random filename, stored outside the public web root,
 * streamed through an access-controlled controller action.
 */
class InterviewFileUploadService
{
    private const ALLOWED_EXTENSIONS = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'xlsx', 'xls', 'txt'];
    private const ALLOWED_MIME_TYPES = [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'image/jpeg',
        'image/png',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'text/plain',
    ];
    private const MAX_SIZE_KB = 10240; // 10MB

    public function validateAndStore(UploadedFile $file): array
    {
        if (! $file->isValid()) {
            throw new \RuntimeException('Upload failed: ' . $file->getErrorString());
        }

        $extension = strtolower($file->getClientExtension());
        if (! in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
            throw new \InvalidArgumentException('File type not accepted. Allowed: PDF, DOC, DOCX, XLS, XLSX, JPG, PNG, TXT.');
        }

        $mime = $file->getMimeType();
        if (! in_array($mime, self::ALLOWED_MIME_TYPES, true)) {
            throw new \InvalidArgumentException('File content does not match an accepted format.');
        }

        if ($file->getSizeByUnit('kb') > self::MAX_SIZE_KB) {
            throw new \InvalidArgumentException('File exceeds the 10MB size limit.');
        }

        $storageDir = WRITEPATH . 'uploads/interviews';
        if (! is_dir($storageDir)) {
            mkdir($storageDir, 0755, true);
        }

        $randomName = bin2hex(random_bytes(16)) . '.' . $extension;
        $file->move($storageDir, $randomName);

        return [
            'file_path'         => 'uploads/interviews/' . $randomName,
            'original_filename' => $file->getClientName(),
            'file_size_kb'      => (int) round($file->getSizeByUnit('kb')),
        ];
    }

    public function absolutePath(string $relativePath): string
    {
        return WRITEPATH . 'uploads/' . ltrim(str_replace('uploads/', '', $relativePath), '/');
    }
}
