<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Models\CannedResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

/**
 * Mobile-app Quick Replies endpoints.
 *
 * Drives the same feature the inbox shows under "Quick Replies" — the
 * snippet manager you open from the inbox sidebar to insert canned text
 * into a reply / compose.
 *
 * Backed by the existing `canned_responses` table + CannedResponse model
 * (the legacy column name; the user-facing label everywhere is
 * "Quick Replies"). Each row has:
 *   • title     — short label shown in the list
 *   • shortcut  — type "/greeting" in the composer to insert the snippet
 *   • content   — the body text inserted into the composer
 *   • scope     — 'personal' (only owner) or 'team' (any workspace member)
 *   • usage_count — bumped on insert; drives the "most used first" sort
 *
 * Field set matches the web inbox UI exactly — no category, no channels.
 */
class QuickRepliesController extends Controller
{
    /**
     * GET /api/v1/mobile/quick-replies
     * Query: ?search=...
     * Always sorted by usage_count desc — same as the inbox sidebar.
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $workspaceId = $user->active_workspace_id;
        if (!$workspaceId) {
            return response()->json(['data' => []]);
        }

        $query = CannedResponse::forWorkspace($workspaceId, $user->id);

        if ($search = trim((string) $request->query('search', ''))) {
            $like = '%' . $search . '%';
            $query->where(function ($w) use ($like) {
                $w->where('title', 'like', $like)
                  ->orWhere('shortcut', 'like', $like)
                  ->orWhere('content', 'like', $like);
            });
        }

        $rows = $query->orderByDesc('usage_count')->orderBy('title')->get();

        return response()->json([
            'data' => $rows->map(fn (CannedResponse $r) => $this->shape($r, $user->id))->all(),
        ]);
    }

    /**
     * GET /api/v1/mobile/quick-replies/{id}
     */
    public function show(Request $request, int $id): JsonResponse
    {
        $user = $request->user();
        $r = CannedResponse::forWorkspace($user->active_workspace_id, $user->id)->find($id);
        if (!$r) {
            return response()->json(['message' => 'Quick reply not found.'], 404);
        }
        return response()->json(['quick_reply' => $this->shape($r, $user->id)]);
    }

    /**
     * POST /api/v1/mobile/quick-replies
     */
    public function store(Request $request): JsonResponse
    {
        $user = $request->user();
        $workspaceId = $user->active_workspace_id;

        $validator = Validator::make($request->all(), [
            'title'    => ['required', 'string', 'max:255'],
            'shortcut' => ['nullable', 'string', 'max:50', 'alpha_dash'],
            'content'  => ['required', 'string', 'max:5000'],
            'scope'    => ['required', 'string', 'in:personal,team'],
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        if ($shortcut = $request->input('shortcut')) {
            $exists = CannedResponse::where('workspace_id', $workspaceId)
                ->where('shortcut', $shortcut)
                ->exists();
            if ($exists) {
                return response()->json([
                    'message' => 'This shortcut is already taken in your workspace.',
                    'errors'  => ['shortcut' => ['Shortcut already taken.']],
                ], 422);
            }
        }

        $r = CannedResponse::create([
            'workspace_id' => $workspaceId,
            'user_id'      => $user->id,
            'title'        => $request->input('title'),
            'shortcut'     => $shortcut ?: null,
            'content'      => $request->input('content'),
            'scope'        => $request->input('scope'),
        ]);

        return response()->json([
            'message'     => 'Quick reply saved.',
            'quick_reply' => $this->shape($r, $user->id),
        ], 201);
    }

    /**
     * PUT /api/v1/mobile/quick-replies/{id}
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $user = $request->user();
        $workspaceId = $user->active_workspace_id;

        $r = CannedResponse::where('workspace_id', $workspaceId)->find($id);
        if (!$r) {
            return response()->json(['message' => 'Quick reply not found.'], 404);
        }

        // Personal scope: only the owner can edit. Team scope: any member can.
        if ($r->scope === 'personal' && $r->user_id !== $user->id) {
            return response()->json(['message' => 'You can only edit your own personal quick replies.'], 403);
        }

        $validator = Validator::make($request->all(), [
            'title'    => ['sometimes', 'required', 'string', 'max:255'],
            'shortcut' => ['nullable', 'string', 'max:50', 'alpha_dash'],
            'content'  => ['sometimes', 'required', 'string', 'max:5000'],
            'scope'    => ['sometimes', 'required', 'string', 'in:personal,team'],
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Shortcut uniqueness (skip if unchanged)
        if ($request->has('shortcut') && $request->input('shortcut') !== $r->shortcut) {
            if ($shortcut = $request->input('shortcut')) {
                $taken = CannedResponse::where('workspace_id', $workspaceId)
                    ->where('shortcut', $shortcut)
                    ->where('id', '!=', $r->id)
                    ->exists();
                if ($taken) {
                    return response()->json([
                        'message' => 'This shortcut is already taken in your workspace.',
                        'errors'  => ['shortcut' => ['Shortcut already taken.']],
                    ], 422);
                }
            }
        }

        $r->update($validator->validated());

        return response()->json([
            'message'     => 'Quick reply updated.',
            'quick_reply' => $this->shape($r->fresh(), $user->id),
        ]);
    }

    /**
     * DELETE /api/v1/mobile/quick-replies/{id}
     */
    public function destroy(Request $request, int $id): JsonResponse
    {
        $user = $request->user();
        $workspaceId = $user->active_workspace_id;

        $r = CannedResponse::where('workspace_id', $workspaceId)->find($id);
        if (!$r) {
            return response()->json(['message' => 'Quick reply not found.'], 404);
        }

        if ($r->scope === 'personal' && $r->user_id !== $user->id) {
            return response()->json(['message' => 'You can only delete your own personal quick replies.'], 403);
        }

        $r->delete();
        return response()->json(['message' => 'Quick reply deleted.']);
    }

    /**
     * POST /api/v1/mobile/quick-replies/{id}/insert
     * Bumps usage_count and returns the content for the composer to insert.
     * Mirrors the web inbox's CannedResponseManager::insert() — same single
     * trigger that updates "most used" sort + returns the snippet text.
     */
    public function insert(Request $request, int $id): JsonResponse
    {
        $user = $request->user();
        $r = CannedResponse::forWorkspace($user->active_workspace_id, $user->id)->find($id);
        if (!$r) {
            return response()->json(['message' => 'Quick reply not found.'], 404);
        }
        $r->increment('usage_count');
        $r->refresh();

        return response()->json([
            'message'     => 'Inserted.',
            'content'     => (string) $r->content,
            'usage_count' => (int) $r->usage_count,
        ]);
    }

    private function shape(CannedResponse $r, int $currentUserId): array
    {
        return [
            'id'          => $r->id,
            'title'       => $r->title,
            'shortcut'    => $r->shortcut,
            'content'     => $r->content,
            'scope'       => $r->scope,
            'is_owner'    => $r->user_id === $currentUserId,
            'usage_count' => (int) $r->usage_count,
            'created_at'  => $r->created_at?->toIso8601String(),
            'updated_at'  => $r->updated_at?->toIso8601String(),
        ];
    }
}
