<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\CustomerDocument;
use App\Services\AuditService;
use App\Services\SecureFileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\StreamedResponse;

class CustomerDocumentController extends Controller
{
    public function store(Request $request, Customer $customer, SecureFileService $files): RedirectResponse
    {
        Gate::authorize('manageDocuments', $customer);
        $data = $request->validate([
            'document_type' => ['required', 'string', 'max:100'],
            'document' => ['required', 'file', 'mimes:pdf,jpg,jpeg,png,webp,doc,docx', 'max:10240'],
            'expiry_date' => ['nullable', 'date'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ]);
        $file = $data['document'];
        $path = $files->store($file, "customers/{$customer->id}/documents");
        $document = $customer->documents()->create([
            'document_type' => $data['document_type'], 'original_name' => $file->getClientOriginalName(),
            'file_path' => $path, 'mime_type' => $file->getMimeType(), 'file_size' => $file->getSize(),
            'expiry_date' => $data['expiry_date'] ?? null, 'notes' => $data['notes'] ?? null, 'uploaded_by' => $request->user()->id,
        ]);
        AuditService::record('customer.document.uploaded', $customer, [], ['document_id' => $document->id, 'document_type' => $document->document_type], $customer->branch_id);
        return redirect()->route('customers.show', [$customer, 'tab' => 'documents'])->with('success', 'Document uploaded.');
    }

    public function download(Request $request, Customer $customer, CustomerDocument $document, SecureFileService $files): StreamedResponse
    {
        Gate::authorize('manageDocuments', $customer);
        abort_unless($document->customer_id === $customer->id, 404);
        AuditService::record('customer.document.downloaded', $customer, [], ['document_id' => $document->id], $customer->branch_id);
        return $files->download($document->file_path, $document->original_name);
    }
}
