<?php

namespace App\Services\Files;

use Illuminate\Support\Facades\DB;

class ExamDraftDownloadNameService
{
    public function build(string $filename, string $subdir): string
    {
        $column = $subdir === 'finals' ? 'final_file' : 'teacher_file';

        $row = DB::table('exam_drafts as ed')
            ->select('ed.version', 'ed.exam_type', 'ed.class_section_id', 'cs.class_section_name')
            ->leftJoin('classSection as cs', 'cs.class_section_id', '=', 'ed.class_section_id')
            ->where('ed.' . $column, $filename)
            ->limit(1)
            ->first();

        $row = $row ? (array) $row : [];

        $classLabel = trim((string) ($row['class_section_name'] ?? ('Class' . ($row['class_section_id'] ?? '0'))));
        $typeLabel = trim((string) ($row['exam_type'] ?? 'Exam'));
        $version = 'v' . max(1, (int) ($row['version'] ?? 1));

        $parts = array_filter([
            $this->slugify($classLabel),
            $this->slugify($typeLabel),
            $version,
        ]);

        return implode('_', $parts);
    }

    private function slugify(string $value): string
    {
        $value = trim($value);
        $value = preg_replace('/[^\p{L}\p{N}]+/u', '_', $value);
        $value = trim($value, '_');
        if ($value === '') {
            return 'Exam';
        }
        return mb_strtolower($value);
    }
}
