<?php

namespace App\Http\Controllers;

use App\Models\CreditNote;
use App\Services\CreditNoteDocumentPresenter;
use App\Services\CreditNotePdfGenerator;
use Illuminate\Http\Request;

class PublicCreditNoteController extends Controller
{
    public function __construct(
        private readonly CreditNoteDocumentPresenter $presenter,
        private readonly CreditNotePdfGenerator $pdfGenerator,
    ) {}

    public function show(string $token, Request $request)
    {
        $creditNote = $this->resolveByToken($token);
        $data = $this->presenter->displayData($creditNote);
        $copies = $data['documentCopies'];
        $copyKey = $request->query('copy', 'original');
        $data['documentCopyLabel'] = $copies[$copyKey] ?? $copies['original'] ?? 'Original Copy';
        $data['forPublic'] = true;
        $data['shareToken'] = $token;

        return view('public.credit-notes.show', $data);
    }

    public function pdf(string $token, Request $request)
    {
        $creditNote = $this->resolveByToken($token);
        $data = $this->presenter->displayData($creditNote);
        $copies = $data['documentCopies'];
        $copyKey = $request->query('copy', 'original');
        $copyLabel = $copies[$copyKey] ?? $copies['original'] ?? 'Original Copy';

        if ($request->boolean('inline')) {
            return $this->pdfGenerator->stream($creditNote, $data, $copyLabel);
        }

        return $this->pdfGenerator->download($creditNote, $data, $copyLabel);
    }

    public function print(string $token, Request $request)
    {
        $creditNote = $this->resolveByToken($token);
        $copyKey = $request->query('copy', 'original');

        return view('admin.credit-notes.print-pdf', [
            'creditNote' => $creditNote,
            'copyKey' => $copyKey,
            'autoprint' => $request->boolean('autoprint', true),
            'backUrl' => route('public.credit-notes.show', $token),
            'pdfUrl' => route('public.credit-notes.pdf', [
                'token' => $token,
                'copy' => $copyKey,
                'inline' => 1,
            ]),
        ]);
    }

    private function resolveByToken(string $token): CreditNote
    {
        $creditNote = CreditNote::with(['items', 'customer', 'invoice'])
            ->where('share_token', $token)
            ->first();

        if (! $creditNote) {
            abort(404, 'This credit note link is invalid or has expired.');
        }

        if ($creditNote->status === 'draft') {
            abort(404, 'This credit note is not available for viewing.');
        }

        return $creditNote;
    }
}
