<?php

namespace App\Services\Auth;

use App\Models\Datmas\Indentitas;
use App\Models\Datmas\Siswa;
use App\Models\Saving\Tregistrasi;
use Illuminate\Database\Eloquent\Collection;

class MobileStudentResolver
{
    public function findByNis(string $nis): ?Siswa
    {
        return Siswa::query()
            ->with(['indentitas', 'kelsis'])
            ->where('nis', $nis)
            ->first();
    }

    public function findByAccountId(string $accountId): ?Siswa
    {
        $identity = Indentitas::query()
            ->with(['siswa.kelsis', 'siswa.indentitas'])
            ->where('nouid', $accountId)
            ->first();

        if ($identity?->siswa) {
            $identity->siswa->setRelation('indentitas', $identity);

            return $identity->siswa;
        }

        return $this->findByNis($accountId);
    }

    public function findByPhoneCandidates(array $phoneCandidates): Collection
    {
        return Siswa::query()
            ->with(['indentitas', 'kelsis'])
            ->whereIn('tel', $phoneCandidates)
            ->get();
    }

    /**
     * Validasi bahwa NIS yang ingin di-switch merupakan siswa dengan nomor HP
     * yang sama dengan siswa pemilik token. Mencegah akses lintas akun.
     */
    public function findSiblingByNis(string $nis, Siswa $tokenOwner): ?Siswa
    {
        if ($tokenOwner->nis === $nis) {
            return $tokenOwner;
        }

        $phone = $tokenOwner->tel;

        if (!$phone) {
            return null;
        }

        $localNumber = preg_replace('/^62/', '', $phone);
        $phoneCandidates = array_values(array_unique(array_filter([
            $phone,
            '0' . $localNumber,
            $localNumber,
            '+' . $phone,
        ])));

        $sibling = Siswa::query()
            ->with(['indentitas', 'kelsis'])
            ->where('nis', $nis)
            ->whereIn('tel', $phoneCandidates)
            ->first();

        // Override relasi indentitas secara eksplisit (konsisten dengan findByAccountId)
        // agar idmen dan idok tersedia lengkap saat siswa di-switch.
        if ($sibling) {
            $identity = Indentitas::query()
                ->with(['siswa.kelsis'])
                ->where('idok', $sibling->getAttribute('id'))
                ->first();

            if ($identity) {
                $sibling->setRelation('indentitas', $identity);
            }
        }

        return $sibling;
    }

    public function accountId(Siswa $siswa): string
    {
        $siswa->loadMissing('indentitas');

        return (string) ($siswa->indentitas?->nouid ?: $siswa->nis);
    }

    public function registration(Siswa $siswa): ?Tregistrasi
    {
        return Tregistrasi::query()
            ->where('nouid', $this->accountId($siswa))
            ->first();
    }

    public function isBlocked(Siswa $siswa): bool
    {
        $siswa->loadMissing('indentitas');

        return ($siswa->indentitas && ! $siswa->indentitas->active)
            || $this->registration($siswa)?->sta === Tregistrasi::STATUS_BLOCKED;
    }
}
