<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ContentBlock extends Model
{
    protected $fillable = [
        'page', 'section_key', 'title', 'body', 'meta', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'meta' => 'array',
        ];
    }

    public static function forPage(string $page): \Illuminate\Support\Collection
    {
        $defaults = static::defaultsForPage($page);

        try {
            $fromDatabase = static::query()
                ->where('page', $page)
                ->get()
                ->keyBy('section_key');
        } catch (\Throwable) {
            return $defaults;
        }

        return $defaults->merge($fromDatabase);
    }

  /** @return \Illuminate\Support\Collection<string, self> */
    public static function defaultsForPage(string $page): \Illuminate\Support\Collection
    {
        $sections = config("content_blocks.pages.{$page}", []);

        return collect($sections)->map(function (array $data, string $sectionKey) use ($page) {
            return new static([
                'page' => $page,
                'section_key' => $sectionKey,
                'title' => $data['title'] ?? null,
                'body' => $data['body'] ?? null,
                'meta' => $data['meta'] ?? [],
            ]);
        });
    }

    public static function section(string $page, string $key): ?self
    {
        return static::query()->where('page', $page)->where('section_key', $key)->first();
    }
}
