<?php

namespace App\Repositories\Admin;

use App\Models\DownloadLink;
use App\Repositories\Interfaces\Admin\DownloadLinkInterface;
use Exception;
use Illuminate\Support\Facades\Log;

class DownloadLinkRepository implements DownloadLinkInterface
{
    public function create(array $data, $downloadable)
    {
        try {
            //dd($data);
            return $downloadable->downloadLinks()->create($data);
        } catch (Exception $e) {
            Log::error('DownloadLink create error: ' . $e->getMessage(), [
                'data' => $data,
                'downloadable' => get_class($downloadable),
            ]);
            throw $e;
        }
    }

    public function update(array $data, int $id)
    {
        try {
            $link = DownloadLink::findOrFail($id);
            $link->update($data);
            return $link;
        } catch (Exception $e) {
            Log::error('DownloadLink update error: ' . $e->getMessage(), [
                'id' => $id,
                'data' => $data,
            ]);
            throw $e;
        }
    }

    public function delete(int $id)
    {
        try {
            $link = DownloadLink::findOrFail($id);
            return $link->delete();
        } catch (Exception $e) {
            Log::error('DownloadLink delete error: ' . $e->getMessage(), [
                'id' => $id,
            ]);
            throw $e;
        }
    }

    public function findById(int $id)
    {
        try {
            return DownloadLink::findOrFail($id);
        } catch (Exception $e) {
            Log::error('DownloadLink findById error: ' . $e->getMessage(), [
                'id' => $id,
            ]);
            throw $e;
        }
    }

    public function statusChange($request)
    {
        try {
            return DownloadLink::where('id', $request->id)->update(['status' => $request->status]);
        } catch (Exception $e) {
            Log::error('DownloadLink status change error: ' . $e->getMessage());
            throw $e;
        }
    }
}