<?php

namespace App\Services;

use App\Models\Student;
use App\Models\Teacher;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class ExternalIdService
{
    /**
     * 处理学生外部ID
     * 如果ID不存在，自动创建用户和学生记录
     */
    public function handleStudentExternalId(int|string $studentId, array $studentData = []): Student
    {
        // student_id是int类型，直接使用
        // 检查学生是否已存在
        $student = Student::where('student_id', $studentId)->first();

        if ($student) {
            Log::info('外部学生ID已存在', ['student_id' => $studentId]);
            return $student;
        }

        // 创建用户记录
        $userData = [
            'user_id' => (string) $studentId, // user表是varchar类型
            'username' => (string) $studentId,
            'password_hash' => Hash::make('password123'),
            'role' => 'student',
            'full_name' => $studentData['name'] ?? '未知学生',
            'email' => $studentId . '@student.edu',
            'is_active' => 1,
        ];

        $user = User::create($userData);

        // 创建学生记录
        $student = Student::create([
            'student_id' => $studentId,
            'name' => $studentData['name'] ?? '未知学生',
            'grade' => $studentData['grade'] ?? '未知年级',
            'class_name' => $studentData['class_name'] ?? '',
            'teacher_id' => $studentData['teacher_id'] ?? null,
            'remark' => $studentData['remark'] ?? '自动创建',
        ]);

        Log::info('外部学生ID自动创建成功', [
            'student_id' => $studentId,
            'user_id' => $user->user_id
        ]);

        return $student;
    }

    /**
     * 处理教师外部ID
     * 如果ID不存在，自动创建用户和教师记录
     */
    public function handleTeacherExternalId(int|string $teacherId, array $teacherData = []): Teacher
    {
        // teacher_id是int类型，直接使用
        // 检查教师是否已存在
        $teacher = Teacher::where('teacher_id', $teacherId)->first();

        if ($teacher) {
            Log::info('外部教师ID已存在', ['teacher_id' => $teacherId]);
            return $teacher;
        }

        // 创建用户记录
        $userData = [
            'user_id' => (string) $teacherId,
            'username' => $teacherData['phone'] ?? (string) $teacherId, // 如果有手机号就用手机号
            'password_hash' => Hash::make('password123'),
            'role' => 'teacher',
            'full_name' => $teacherData['name'] ?? '未知教师',
            'email' => $teacherId . '@teacher.edu',
            'is_active' => 1,
        ];

        $user = User::create($userData);

        // 创建教师记录
        $teacher = Teacher::create([
            'teacher_id' => $teacherId,
            'teacher_string_id' => $teacherData['teacher_string_id'] ?? null,
            'user_id' => $user->user_id,
            'name' => $teacherData['name'] ?? '未知教师',
            'subject' => $teacherData['subject'] ?? '数学',
        ]);

        Log::info('外部教师ID自动创建成功', [
            'teacher_id' => $teacherId,
            'user_id' => $user->user_id
        ]);

        return $teacher;
    }

    /**
     * 批量处理学生外部ID
     */
    public function handleBatchStudentExternalIds(array $studentIds): array
    {
        $results = [];

        foreach ($studentIds as $studentId => $studentData) {
            try {
                $student = $this->handleStudentExternalId($studentId, $studentData);
                $results[$studentId] = ['success' => true, 'student' => $student];
            } catch (\Exception $e) {
                Log::error('批量处理学生ID失败', [
                    'student_id' => $studentId,
                    'error' => $e->getMessage()
                ]);
                $results[$studentId] = ['success' => false, 'error' => $e->getMessage()];
            }
        }

        return $results;
    }

    /**
     * 验证外部ID格式
     */
    public function validateExternalId(int|string $externalId, string $type = 'student'): bool
    {
        $externalId = (string) $externalId;

        // 基本格式验证
        if (empty($externalId)) {
            return false;
        }

        // 长度验证（1-64字符）
        if (strlen($externalId) > 64 || strlen($externalId) < 1) {
            return false;
        }

        // 字符验证（允许字母、数字、下划线、连字符）
        if (!preg_match('/^[a-zA-Z0-9_-]+$/', $externalId)) {
            return false;
        }

        return true;
    }

    /**
     * 通过外部ID获取学生信息（包含关联）
     */
    public function getStudentWithRelations(int|string $studentId): ?Student
    {
        return Student::with(['teacher.user', 'user'])
            ->where('student_id', $studentId)
            ->first();
    }

    /**
     * 通过外部ID获取教师信息（包含关联）
     */
    public function getTeacherWithRelations(int|string $teacherId): ?Teacher
    {
        return Teacher::with(['user', 'students'])
            ->where('teacher_id', $teacherId)
            ->first();
    }

    /**
     * 获取教师的学生列表
     */
    public function getTeacherStudents(int|string $teacherId): Collection
    {
        return Student::with(['user'])
            ->where('teacher_id', $teacherId)
            ->orderBy('name')
            ->get();
    }

    /**
     * 获取学生的试卷列表
     */
    public function getStudentPapers(int|string $studentId): Collection
    {
        return Student::find($studentId)
            ?->papers()
            ->with(['paperQuestions.question'])
            ->orderBy('created_at', 'desc')
            ->get() ?? collect();
    }

    /**
     * 检查外部ID是否存在
     */
    public function studentExists(int|string $studentId): bool
    {
        return Student::where('student_id', $studentId)->exists();
    }

    /**
     * 检查外部ID是否存在
     */
    public function teacherExists(int|string $teacherId): bool
    {
        return Teacher::where('teacher_id', $teacherId)->exists();
    }
}
