<?php

namespace App\Modules\Notification\Models;

use App\Modules\Notification\Entities\TelegramAccount;
use CodeIgniter\Model;

/**
 * Telegram Account Model
 * 
 * Handles database operations for Telegram accounts.
 */
class TelegramAccountModel extends Model
{
    protected $table            = 'telegram_accounts';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = TelegramAccount::class;
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'telegram_user_id',
        'username',
        'first_name',
        'last_name',
        'is_verified',
        'parent_id',
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules = [
        'telegram_user_id' => 'required|integer|is_unique[telegram_accounts.telegram_user_id,id,{id}]',
        'username'         => 'permit_empty|max_length[255]',
        'first_name'       => 'permit_empty|max_length[255]',
        'last_name'        => 'permit_empty|max_length[255]',
        'is_verified'      => 'permit_empty|in_list[0,1]',
    ];

    protected $validationMessages = [];
    protected $skipValidation     = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    /**
     * Find Telegram account by telegram_user_id
     * 
     * @param int $telegramUserId
     * @return TelegramAccount|null
     */
    public function findByTelegramUserId(int $telegramUserId): ?TelegramAccount
    {
        return $this->where('telegram_user_id', $telegramUserId)->first();
    }

    /**
     * Get telegram_user_id list for all linked parents of a student
     * 
     * @param int $studentId
     * @return array<int> List of telegram_user_id
     */
    public function getTelegramUserIdsByStudentId(int $studentId): array
    {
        $db = \Config\Database::connect();
        $builder = $db->table('student_parents AS sp');
        $builder->select('t.telegram_user_id');
        $builder->join('telegram_accounts AS t', 't.parent_id = sp.parent_id AND t.is_verified = 1', 'inner');
        $builder->where('sp.student_id', $studentId);
        $rows = $builder->get()->getResultArray();

        $ids = [];
        foreach ($rows as $row) {
            $ids[] = (int) $row['telegram_user_id'];
        }
        return array_values(array_unique($ids));
    }
}
