<?php

namespace App\Livewire\Catalog;

use App\Livewire\Concerns\ManagesResource;
use App\Models\SaasProduct;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Livewire\Attributes\Title;
use Livewire\Component;

/**
 * The Thinkrax portfolio.
 *
 * Adding a row here plus a block in `config/thinkrax.php` is the entire cost
 * of putting a second product on this panel — no other screen changes.
 */
#[Title('Products')]
class Products extends Component
{
    use ManagesResource;

    protected function modelClass(): string
    {
        return SaasProduct::class;
    }

    protected function resourceLabel(): string
    {
        return 'Product';
    }

    protected function formFields(): array
    {
        return [
            'name' => '',
            'slug' => '',
            'tagline' => '',
            'description' => '',
            'app_url' => '',
            'accent_color' => '#2563eb',
            'is_active' => true,
            'sort_order' => 0,
        ];
    }

    protected function formRules(): array
    {
        return [
            'name' => 'required|string|max:120',
            'slug' => 'required|string|max:120|alpha_dash|unique:saas_products,slug',
            'tagline' => 'nullable|string|max:180',
            'description' => 'nullable|string|max:2000',
            'app_url' => 'nullable|url|max:255',
            'accent_color' => 'nullable|string|max:20',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0|max:9999',
        ];
    }

    protected function searchableColumns(): array
    {
        return ['name', 'slug', 'tagline'];
    }

    protected function defaultSort(): array
    {
        return ['sort_order', 'asc'];
    }

    protected function sortableColumns(): array
    {
        return ['name', 'slug', 'sort_order', 'created_at'];
    }

    /** Keep the slug in step with the name until the record exists. */
    public function updatedFormName(string $value): void
    {
        if (! $this->editingId) {
            $this->form['slug'] = Str::slug($value);
        }
    }

    protected function beforeSave(array $data): array
    {
        $data['slug'] = Str::slug($data['slug'] ?: $data['name']);

        return $data;
    }

    protected function cannotDeleteReason(Model $record): ?string
    {
        if ($record->tenants()->exists()) {
            return 'Shops are subscribed to this product. Deactivate it instead — deleting would orphan their billing history.';
        }

        if ($record->plans()->exists()) {
            return 'Delete or move this product’s plans first.';
        }

        return null;
    }

    /** Slug is immutable once tenants exist: products key their config off it. */
    public function slugIsLocked(): bool
    {
        return $this->editingId
            && SaasProduct::find($this->editingId)?->tenants()->exists();
    }

    protected function baseQuery(): \Illuminate\Database\Eloquent\Builder
    {
        return SaasProduct::query()->withCount(['tenants', 'plans']);
    }

    public function render()
    {
        return view('livewire.catalog.products', [
            'rows' => $this->rows(),
            'known' => array_keys(config('thinkrax.products', [])),
        ]);
    }
}
