<?php

namespace App\Http\Controllers;

use App\Http\Requests\AiTemplateRequest;
use App\Http\Requests\AiTemplateUpdateRequest;
use App\Http\Services\AiService;
use App\Models\AiTemplate;
use Illuminate\Http\Request;

class AiModuleController extends Controller
{
    protected $aiService;

    public function __construct(AiService $analyticsService)
    {
        $this->aiService = new AiService();
    }

    public function generate(Request $request)
    {
        try {
            $data = $request->validate([
                'prompt' => 'required|string',
                'module' => 'required|string|in:text,image,video',
                'conversation_history' => 'nullable|array',
                'conversation_history.*.role' => 'nullable|string|in:user,assistant',
                'conversation_history.*.content' => 'nullable|string',
            ]);

            $module = $data['module'];

            switch ($module) {
                case 'text':
                    $serviceResult = $this->aiService->generateTextContent($request);
                    $httpStatus = $serviceResult['status'] ? 200 : 422;
                    return response()->json([
                        'status' => $serviceResult['status'] ? 'success' : 'error',
                        'message' => $serviceResult['message'],
                        'content' => $serviceResult['content'] ?? null,
                    ], $httpStatus);

                case 'image':
                    $serviceResult = $this->aiService->generateImageContent($request);
                    $httpStatus = $serviceResult['status'] ? 200 : 422;
                    return response()->json([
                        'status' => $serviceResult['status'] ? 'success' : 'error',
                        'message' => $serviceResult['message'],
                        'urls' => $serviceResult['image_content'] ?? [],
                    ], $httpStatus);

                case 'video':
                    $serviceResult = $this->aiService->generateVideoContent($request);
                    $httpStatus = $serviceResult['status'] ? 200 : 422;
                    return response()->json([
                        'status' => $serviceResult['status'] ? 'success' : 'error',
                        'message' => $serviceResult['message'],
                        'urls' => $serviceResult['video_content'] ?? [],
                    ], $httpStatus);

                default:
                    return response()->json([
                        'status' => 'error',
                        'message' => 'Invalid module requested',
                    ], 422);
            }
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed: ' . json_encode($e->errors()),
                'errors' => $e->errors(),
                'request_data' => $request->only(['prompt', 'module', 'conversation_history']),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An unexpected error occurred: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function storeTemplate(AiTemplateRequest $request)
    {
        $response = $this->aiService->saveTemplate($request);

        if (isset($response['error']) && $response['error'])
            return redirect()->back()->with('error', $response['error']);

        return redirect()->back()->with('success', $response['success']);
    }

    public function updateTemplate(AiTemplateUpdateRequest $request)
    {
        $response = $this->aiService->updateTemplate($request);

        if (isset($response['error']) && $response['error'])
            return redirect()->back()->with('error', $response['error']);

        return redirect()->back()->with('success', $response['success']);
    }

    public function deleteTemplate(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:ai_templates,id'
        ]);

        $aiTemplate = AiTemplate::findOrFail($request->input('id'));
        $aiTemplate->delete();

        return redirect()->back()->with('success', 'Ai Template Deleted');

    }



}
