<?php

namespace App\Http\Controllers;

use App\Models\BlacklistRecord;
use App\Models\Customer;
use App\Services\AuditService;
use App\Services\CustomerRiskService;
use App\Services\SecureFileService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;

class BlacklistController extends Controller
{
    public function store(Request $request, Customer $customer, SecureFileService $files, CustomerRiskService $risk): RedirectResponse
    {
        Gate::authorize('manageWatchlist', $customer);
        $data = $request->validate([
            'type' => ['required', Rule::in(['watchlist','blacklist'])], 'reason' => ['required','string','max:255'],
            'notes' => ['nullable','string','max:3000'], 'supporting_document' => ['nullable','file','mimes:pdf,jpg,jpeg,png,webp','max:10240'],
        ]);
        $file = $data['supporting_document'] ?? null; unset($data['supporting_document']);
        if ($file) { $data['supporting_document_path'] = $files->store($file, "customers/{$customer->id}/watchlist"); }
        $data['added_by'] = $request->user()->id;
        $record = $customer->blacklistRecords()->create($data);
        $risk->refreshWithHistory($customer, $record->type.'_record_added');
        AuditService::record('customer.watchlist.created', $customer, [], ['record_id'=>$record->id,'type'=>$record->type,'reason'=>$record->reason], $customer->branch_id);
        return redirect()->route('customers.show', [$customer, 'tab' => 'blacklist'])->with('success', ucfirst($record->type).' record added.');
    }

    public function resolve(Request $request, Customer $customer, BlacklistRecord $record, CustomerRiskService $risk): RedirectResponse
    {
        Gate::authorize('manageWatchlist', $customer);
        abort_unless($record->customer_id === $customer->id, 404);
        abort_unless($record->status === 'active', 422);
        $request->validate(['resolution_notes' => ['nullable','string','max:2000']]);
        $before = $record->toArray();
        $record->update(['status'=>'resolved','resolved_at'=>now(),'resolved_by'=>$request->user()->id,'notes'=>trim(($record->notes ? $record->notes."\n" : '').($request->input('resolution_notes') ?? ''))]);
        $risk->refreshWithHistory($customer, $record->type.'_record_resolved');
        AuditService::record('customer.watchlist.resolved', $customer, $before, $record->fresh()->toArray(), $customer->branch_id);
        return redirect()->route('customers.show', [$customer, 'tab' => 'blacklist'])->with('success', 'Record resolved.');
    }
}
