<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class StudentIdService
{
    /**
     * 生成新的学生ID
     *
     * @return string
     */
    public static function generateStudentId(): string
    {
        $timestamp = time();

        // 获取当前时间戳下的序号
        $sequence = self::getNextSequence($timestamp);

        return "stu_{$timestamp}_{$sequence}";
    }

    /**
     * 获取下一个序号
     *
     * @param int $timestamp
     * @return int
     */
    private static function getNextSequence(int $timestamp): int
    {
        // 查找相同时间戳的最后一个序号
        $lastStudent = DB::table('students')
            ->where('student_id', 'like', "stu_{$timestamp}_%")
            ->orderByRaw('CAST(SUBSTRING_INDEX(student_id, "_", -1) AS UNSIGNED) DESC')
            ->first();

        if ($lastStudent) {
            // 提取序号并递增
            $lastSequence = (int) substr($lastStudent->student_id, strrpos($lastStudent->student_id, '_') + 1);
            return $lastSequence + 1;
        }

        return 0;
    }

    /**
     * 验证学生ID格式是否正确
     *
     * @param string $studentId
     * @return bool
     */
    public static function validateStudentIdFormat(string $studentId): bool
    {
        return preg_match('/^stu_\d+_\d+$/', $studentId) === 1;
    }
}