<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * All feature models extend this class.
 * It automatically scopes every query to the authenticated church
 * and enforces soft-delete filtering.
 */
abstract class BaseModel extends Model
{
    protected $useSoftDeletes   = true;
    protected $deletedField     = 'deleted_at';
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $returnType       = 'array';

    // Set by ChurchScopeFilter via ChurchContext singleton
    protected ?int $churchId = null;

    public function setChurchId(int $id): static
    {
        $this->churchId = $id;
        return $this;
    }

    // ------------------------------------------------------------------
    // Scope application — called before every builder usage
    // ------------------------------------------------------------------

    protected function applyChurchScope(): static
    {
        if ($this->churchId !== null) {
            $this->where($this->table . '.church_id', $this->churchId);
        }
        return $this;
    }

    // ------------------------------------------------------------------
    // Overrides to inject the church scope transparently
    // ------------------------------------------------------------------

    public function findAll(?int $limit = null, int $offset = 0): array
    {
        $this->applyChurchScope();
        return parent::findAll($limit, $offset);
    }

    public function find($id = null): array|object|null
    {
        $this->applyChurchScope();
        return parent::find($id);
    }

    public function first(): array|object|null
    {
        $this->applyChurchScope();
        return parent::first();
    }

    // ------------------------------------------------------------------
    // Helpers used by controllers
    // ------------------------------------------------------------------

    /** Find a record by its UUID, scoped to the church. Returns null if not found or belongs to another church. */
    public function findByUuid(string $uuid): ?array
    {
        $this->applyChurchScope();
        return $this->where($this->table . '.uuid', $uuid)->first();
    }

    /** Paginate results with church scope already applied. */
    public function scopedPaginate(int $perPage = 20): array
    {
        $this->applyChurchScope();
        $page    = (int) (service('request')->getGet('page') ?? 1);
        $offset  = ($page - 1) * $perPage;
        $total   = $this->countAllResults(false);
        $results = $this->findAll($perPage, $offset);

        return [
            'data'     => $results,
            'meta'     => [
                'total'        => $total,
                'per_page'     => $perPage,
                'current_page' => $page,
                'last_page'    => (int) ceil($total / $perPage),
            ],
        ];
    }
}
