<?php

namespace App\Services\Parents;

use App\Models\User;
use Illuminate\Support\Facades\DB;

/**
 * Maps the logged-in parent-family account to the primary parent's user id
 * (stored on {@see \App\Models\Student::$parent_id}), matching legacy
 * {@see \App\Controllers\ParentReportCardController::resolvePrimaryParentId}.
 */
final class PrimaryParentUserResolver
{
    public function resolveFromUser(?User $user): ?int
    {
        if ($user === null) {
            return null;
        }

        return $this->resolveFromCredentials((int) $user->id, (string) ($user->user_type ?? ''));
    }

    /**
     * @param int $userId Session user id (may be secondary/tertiary login).
     */
    public function resolveFromCredentials(int $userId, string $userType): ?int
    {
        $userType = strtolower(trim($userType));
        if ($userType === 'primary') {
            return $userId > 0 ? $userId : null;
        }

        if ($userType === 'secondary') {
            $row = DB::table('parents')
                ->select('parent_id')
                ->where('secondparent_user_id', $userId)
                ->first();

            return $row ? (int) ($row->parent_id ?? 0) ?: null : null;
        }

        if ($userType === 'tertiary') {
            $row = DB::table('authorized_users')
                ->select('user_id')
                ->where('authorized_user_id', $userId)
                ->first();

            return $row ? (int) ($row->user_id ?? 0) ?: null : null;
        }

        return $userId > 0 ? $userId : null;
    }
}
