<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Models\EmailTemplate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

/**
 * Mobile email template picker.
 *
 * The web UI ships ~50 prebuilt templates as workspace_id=NULL +
 * is_default=true; workspaces can also save their own. The Flutter
 * composer needs to:
 *   1. browse available templates with thumbnails (preview)
 *   2. load the chosen template's blocks JSON to pre-fill the editor
 *
 * Endpoints (mounted under /api/v1/mobile/email-templates):
 *   GET /                    list with thumbnails, category, is_default
 *   GET /{id}                full body for editor pre-fill
 *   POST /{id}/use           records usage_count++ (analytics)
 */
class EmailTemplatesController extends Controller
{
    /**
     * GET /api/v1/mobile/email-templates
     * Query: ?category=onboarding&search=welcome&page=1&per_page=25
     *
     * Returns BOTH workspace-owned templates AND platform defaults
     * (workspace_id IS NULL). Defaults sort last within each category
     * so the user's own templates appear first.
     */
    public function index(Request $request): JsonResponse
    {
        $workspaceId = $request->user()->active_workspace_id;

        $q = EmailTemplate::query()
            ->where(function ($w) use ($workspaceId) {
                $w->where('workspace_id', $workspaceId)
                  ->orWhereNull('workspace_id');
            });

        if ($category = trim((string) $request->query('category', ''))) {
            $q->where('category', $category);
        }
        if ($search = trim((string) $request->query('search', ''))) {
            $q->where('name', 'like', '%' . $search . '%');
        }

        $perPage = min(max((int) $request->query('per_page', 25), 1), 100);

        $q->orderByRaw('workspace_id IS NULL ASC') // user templates first
          ->orderBy('category')
          ->orderBy('name');

        $paginator = $q->paginate($perPage);

        return response()->json([
            'data' => collect($paginator->items())->map(fn (EmailTemplate $t) => $this->shape($t))->all(),
            'meta' => [
                'current_page' => $paginator->currentPage(),
                'per_page'     => $paginator->perPage(),
                'total'        => $paginator->total(),
                'has_more'     => $paginator->hasMorePages(),
            ],
        ]);
    }

    /**
     * GET /api/v1/mobile/email-templates/{id}
     *
     * Returns the full template including the blocks array so the
     * composer can hydrate its editor. Platform defaults (workspace_id
     * IS NULL) are readable by every workspace.
     */
    public function show(Request $request, int $id): JsonResponse
    {
        $workspaceId = $request->user()->active_workspace_id;

        $tpl = EmailTemplate::where(function ($w) use ($workspaceId) {
            $w->where('workspace_id', $workspaceId)->orWhereNull('workspace_id');
        })->find($id);

        if (!$tpl) {
            return response()->json(['message' => 'Template not found.'], 404);
        }

        return response()->json([
            'data' => array_merge($this->shape($tpl), [
                'blocks' => is_array($tpl->blocks) ? $tpl->blocks : null,
            ]),
        ]);
    }

    /**
     * POST /api/v1/mobile/email-templates/{id}/use
     *
     * Bumps usage_count so the "Most used templates" sort in the
     * composer reflects real picks. Called by the Flutter app after
     * the user selects a template — fire-and-forget; failures here
     * never block the composer.
     */
    public function recordUse(Request $request, int $id): JsonResponse
    {
        $workspaceId = $request->user()->active_workspace_id;

        $tpl = EmailTemplate::where(function ($w) use ($workspaceId) {
            $w->where('workspace_id', $workspaceId)->orWhereNull('workspace_id');
        })->find($id);

        if ($tpl) {
            $tpl->increment('usage_count');
        }

        return response()->json(['message' => 'OK']);
    }

    private function shape(EmailTemplate $t): array
    {
        return [
            'id'             => $t->id,
            'name'           => $t->name,
            'category'       => $t->category,
            'is_default'     => (bool) $t->is_default,
            'is_platform'    => $t->workspace_id === null,
            'usage_count'    => (int) ($t->usage_count ?? 0),
            'thumbnail_url'  => $t->thumbnail_path
                ? Storage::disk('public')->url($t->thumbnail_path)
                : null,
            'created_at'     => $t->created_at?->toIso8601String(),
        ];
    }
}
