<?php

namespace App\Models;

use App\Services\StudentIdService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Student extends Model
{
    use HasFactory;

    protected $table = 'students';

    protected $primaryKey = 'student_id';

    public $incrementing = false;

    protected $keyType = 'int';

    protected $fillable = [
        'student_id',
        'name',
        'grade',
        'class_name',
        'teacher_id',
        'remark',
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();

        // 在创建学生时自动生成ID并创建用户记录
        static::creating(function (Student $student) {
            if (empty($student->student_id)) {
                $student->student_id = StudentIdService::generateStudentId();
            }

            // 创建对应的用户记录（需要在学生记录之前创建，因为存在外键约束）
            $existingUser = \App\Models\User::where('user_id', $student->student_id)->first();
            if (!$existingUser) {
                \App\Models\User::create([
                    'user_id' => $student->student_id,
                    'username' => $student->student_id,
                    'password_hash' => \Hash::make('password123'), // 默认密码，实际使用时应该修改
                    'role' => 'student',
                    'full_name' => $student->name,
                    'email' => $student->student_id . '@student.edu',
                    'is_active' => 1,
                ]);
            }
        });

        // 在学生数据变更后清除缓存
        static::saved(function (Student $student) {
            \App\Filament\Resources\StudentResource::clearCaches();
        });

        static::deleted(function (Student $student) {
            \App\Filament\Resources\StudentResource::clearCaches();
        });
    }

    public function teacher(): BelongsTo
    {
        return $this->belongsTo(Teacher::class, 'teacher_id', 'teacher_id');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'student_id', 'user_id');
    }

    /**
     * 获取学生的试卷列表
     */
    public function papers()
    {
        return $this->hasMany(\App\Models\Paper::class, 'student_id', 'student_id');
    }

    /**
     * 获取学生最近生成的试卷
     */
    public function recentPapers($limit = 10)
    {
        return $this->hasMany(\App\Models\Paper::class, 'student_id', 'student_id')
            ->orderBy('created_at', 'desc')
            ->limit($limit);
    }

    /**
     * 获取学生的学情报告
     */
    public function reports()
    {
        return $this->hasMany(\App\Models\StudentReport::class, 'student_id', 'student_id');
    }

    /**
     * 获取学生最新的学情报告
     */
    public function latestReport()
    {
        return $this->hasOne(\App\Models\StudentReport::class, 'student_id', 'student_id')
            ->latest('generated_at');
    }
}
