<?php

namespace App\Http\Controllers;

use App\Services\ApprovalService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class ApprovalController extends Controller
{
    public function __construct(
        private readonly ApprovalService $service
    ) {}

    /**
     * 기안함
     */
    public function drafts(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.drafts'));
        }

        return view('approvals.drafts');
    }

    /**
     * 기안 작성
     */
    public function create(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.create'));
        }

        $forms = $this->service->getApprovalForms();
        $lines = $this->service->getApprovalLines();

        return view('approvals.create', compact('forms', 'lines'));
    }

    /**
     * 기안 수정
     */
    public function edit(Request $request, int $id): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.edit', $id));
        }

        $approval = $this->service->getApproval($id);

        if (! $approval->isEditable() || $approval->drafter_id !== auth()->id()) {
            abort(403, '수정할 수 없습니다.');
        }

        $forms = $this->service->getApprovalForms();
        $lines = $this->service->getApprovalLines();

        return view('approvals.edit', compact('approval', 'forms', 'lines'));
    }

    /**
     * 결재 상세
     */
    public function show(Request $request, int $id): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.show', $id));
        }

        $approval = $this->service->getApproval($id);

        return view('approvals.show', compact('approval'));
    }

    /**
     * 결재 대기함
     */
    public function pending(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.pending'));
        }

        return view('approvals.pending');
    }

    /**
     * 참조함
     */
    public function references(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.references'));
        }

        return view('approvals.references');
    }

    /**
     * 완료함
     */
    public function completed(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('approvals.completed'));
        }

        return view('approvals.completed');
    }
}
