<?php

namespace App\Services;

use App\Models\AdmissionApplication;
use App\Models\Family;
use App\Models\Student;
use Illuminate\Support\Facades\DB;

class AdmissionService
{
    public function __construct(private StudentService $students)
    {
    }

    public function approve(AdmissionApplication $application): void
    {
        $application->update(['status' => 'approved']);
    }

    public function reject(AdmissionApplication $application): void
    {
        $application->update(['status' => 'rejected']);
    }

    public function waitlist(AdmissionApplication $application): void
    {
        $application->update(['status' => 'waiting']);
    }

    /**
     * Enroll an approved application: create (or reuse) a family, then create
     * the student record and mark the application enrolled.
     */
    public function enroll(AdmissionApplication $application): Student
    {
        return DB::transaction(function () use ($application) {
            $family = $application->family;

            if (! $family) {
                $family = Family::create([
                    'branch_id' => $application->branch_id,
                    'family_code' => Family::nextCode($application->branch_id),
                    'father_name' => $application->parent_name,
                    'father_mobile' => $application->contact,
                    'email' => $application->email,
                ]);
            }

            $student = $this->students->create([
                'family_id' => $family->id,
                'class_id' => $application->class_id,
                'name' => $application->student_name,
                'gender' => $application->gender,
                'date_of_birth' => $application->date_of_birth,
            ]);

            $application->update([
                'status' => 'enrolled',
                'family_id' => $family->id,
                'enrolled_student_id' => $student->id,
            ]);

            return $student;
        });
    }
}
