<?php

namespace App\Http\Controllers\api\v1;

use App\Exceptions\InternalServerException;
use App\Exceptions\UnauthorizedException;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class DeployController extends Controller
{
    public function migrate(Request $request): JsonResponse
    {
        $deploySecret = config('app.deploy_secret');

        throw_if(
            empty($deploySecret),
            InternalServerException::class,
            'Deploy secret not configured'
        );

        // constant-time comparison to prevent timing attacks
        if (! hash_equals($deploySecret, (string) $request->header('X-Deploy-Secret'))) {
            throw new UnauthorizedException('Unauthorized');
        }

        Artisan::call('migrate', ['--force' => true]);
        Artisan::call('config:cache');
        Artisan::call('route:cache');
        Artisan::call('view:cache');

        return response()->json([
            'status'    => 'ok',
            'message'   => 'Migrations and cache refreshed',
            'timestamp' => now()->toIso8601String(),
        ]);
    }
}
