<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\MobileConfig\MobileConfigService;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;

class MobileConfigController extends Controller
{
    public function __construct(
        protected MobileConfigService $service
    ) {}

    #[OA\Get(
        path: '/mobile/sync',
        operationId: 'getMobileConfig',
        tags: ['Mobile'],
        summary: 'Get mobile app configuration',
        description: 'Returns cached mobile configuration including theme, flags, and assets.',
        parameters: [
            new OA\Parameter(
                name: 'p',
                in: 'query',
                description: 'Platform (ios/android)',
                required: false,
                schema: new OA\Schema(type: 'string')
            ),
            new OA\Parameter(
                name: 'v',
                in: 'query',
                description: 'App Version',
                required: false,
                schema: new OA\Schema(type: 'string')
            ),
        ],
        responses: [
            new OA\Response(
                response: 200,
                description: 'Successful operation',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'status', type: 'string', example: 'success'),
                        new OA\Property(property: 'version', type: 'string', example: '1.1.0'),
                        new OA\Property(property: 'data', type: 'object'),
                    ]
                )
            ),
        ]
    )]
    public function sync(Request $request)
    {
        $config = $this->service->all();
        $etag = md5(json_encode($config));

        if ($request->hasHeader('If-None-Match') && $request->header('If-None-Match') === $etag) {
            return response()->json([], 304);
        }

        return response()->json([
            'status' => 'success',
            'version' => '1.1.0',
            'last_updated' => now()->toIso8601String(),
            'data' => $config,
        ])->header('ETag', $etag);
    }
}
