<?php

namespace App\Http\Controllers;

use App\DealRepository;
use App\Http\Requests\AddDealMessage;
use App\Http\Requests\AddDealNote;
use App\Http\Requests\AssignDeal;
use App\Http\Requests\SetDealStatus;
use App\Http\Requests\StoreDeal;
use App\Http\Resources\DealList;
use App\Http\Resources\DealResource;
use Illuminate\Support\Facades\Auth;
use Mtc\MercuryDataModels\DealBuilder\Deal;

class DealController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): DealList
    {
        return new DealList(
            Deal::query()
                ->where('status_id', '>', 0)
                ->latest()
                ->paginate()
        );
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreDeal $request, DealRepository $repository): DealResource
    {
        $deal = $repository->create($request->validated(), Auth::id());
        return new DealResource($deal);
    }

    /**
     * Display the specified resource.
     */
    public function show(Deal $deal): DealResource
    {
        return new DealResource($deal);
    }

    public function destroy(Deal $deal)
    {
        $deal->delete();
        return response('ok');
    }

    public function assignUser(AssignDeal $request, Deal $deal, DealRepository $repository): DealResource
    {
        $repository->assignUser($deal, $request->input('user_id'));
        return new DealResource($deal);
    }

    public function addNote(AddDealNote $request, Deal $deal, DealRepository $repository): DealResource
    {
        $files = $request->hasFile('files') ? $request->file('files') : [];
        $repository->addNote($deal, Auth::id(), $request->input('message'), $files);
        return new DealResource($deal);
    }

    public function addMessage(AddDealMessage $request, Deal $deal, DealRepository $repository): DealResource
    {
        $files = $request->hasFile('files') ? $request->file('files') : [];
        $repository->addMessage($deal, $request->input('message'), Auth::id(), $files);
        return new DealResource($deal);
    }

    public function setStatus(SetDealStatus $request, Deal $deal, DealRepository $repository): DealResource
    {
        $repository->updateStatus($deal, $request->input('status_id'), Auth::id());
        return new DealResource($deal);
    }
}
