<?php

namespace App\Http\Controllers\Api;

use App\Models\Downloads;
use App\Models\Episode;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DownloadApiController extends Controller
{
    /**
     * Get Download URL for users who are not logged in.
     */
    public function getDownload(Request $request)
    {
        $validated = $request->validate([
            'episode_id'  => 'required',
            'captcha'     => 'required|captcha'
        ]);

        $episode = Episode::where('id', $request->input('episode_id'))->firstOrFail();

        // Increase download count, as we assume the user
        // downloads after submitting the captcha
        $download = Downloads::find($episode->getDownloadByType('FHD')->id);
        $oldCount = $download->count;
        $download->count++;
        $download->save();

        return response()->json([
            'message'           => 'success',
            'download_url'      => $download->url,
            'download_count'    => $oldCount,
        ], 200);
    }
}
