<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PartnerCredential extends Model
{
    protected $table = 'partner_credentials';

    protected $guarded = ['id'];

    protected $casts = [
        'is_active' => 'boolean',
        'rate_limit_per_minute' => 'integer',
        'user_id' => 'integer',
    ];

    protected $hidden = ['api_key_hash'];

    public function clickRefs()
    {
        return $this->hasMany(PartnerClickRef::class, 'partner_id', 'id');
    }

    /**
     * Plaintext keys are never stored; lookup is by sha256 of the presented key.
     *
     * @param string $plainKey
     * @return static|null
     */
    public static function findByApiKey($plainKey)
    {
        if (!is_string($plainKey) || strlen($plainKey) < 20) {
            return null;
        }
        return static::where('api_key_hash', hash('sha256', $plainKey))
            ->where('is_active', true)
            ->first();
    }
}
