<?php

namespace Modules\Auth\Models;

use CodeIgniter\Model;

class PasswordHistoryModel extends Model
{
    protected $table         = 'password_history';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = ['user_id', 'password_hash', 'created_at'];

    public function record(int $userId, string $hash): void
    {
        $this->insert([
            'user_id'       => $userId,
            'password_hash' => $hash,
            'created_at'    => date('Y-m-d H:i:s'),
        ]);
    }

    public function recentHashes(int $userId, int $limit): array
    {
        $rows = $this->where('user_id', $userId)
            ->orderBy('created_at', 'DESC')
            ->findAll($limit);

        return array_column($rows, 'password_hash');
    }

    public function pruneOlderThan(int $userId, int $keep): void
    {
        $ids = $this->where('user_id', $userId)
            ->orderBy('created_at', 'DESC')
            ->findAll();

        $stale = array_slice($ids, $keep);
        foreach ($stale as $row) {
            $this->delete($row['id']);
        }
    }
}
