<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlockedDomainPattern;
use App\Models\Setting;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class BlockedDomainPatternController extends Controller
{
    use LogsAdminActivity;

    public function index()
    {
        $patterns = BlockedDomainPattern::orderBy('pattern')->paginate(50);
        // PRC-319 / A-8 — enforcement setting moved from /admin/settings tab
        // onto this page (collapsible card at the top). Reader is unchanged
        // (DomainService still reads `domain_blocked_pattern_enforcement`).
        $enforcement = (string) Setting::getValue('domain_blocked_pattern_enforcement', 'block');

        return view('admin.blocked-domain-patterns.index', compact('patterns', 'enforcement'));
    }

    /**
     * PRC-319 / A-8 — persist enforcement mode (block/warn/disabled).
     * Single-field form on the index page; full validation kept tight
     * since the value drives a runtime guard in DomainService.
     */
    public function saveSettings(Request $request): RedirectResponse
    {
        $this->authorize('manage blocked_domain_patterns');

        $data = $request->validate([
            'domain_blocked_pattern_enforcement' => 'required|string|in:block,warn,disabled',
        ]);

        Setting::set('domain_blocked_pattern_enforcement', $data['domain_blocked_pattern_enforcement']);

        $this->logCustomAction(
            action: 'updated',
            model: BlockedDomainPattern::query()->getModel(),
            changes: ['domain_blocked_pattern_enforcement' => $data['domain_blocked_pattern_enforcement']],
            description: "Blocked pattern enforcement mode set to {$data['domain_blocked_pattern_enforcement']}",
        );

        return redirect()->route('admin.blocked-domain-patterns.index')
            ->with('success', __('admin/blocked-domain-patterns.settings_saved'));
    }

    public function create()
    {
        return view('admin.blocked-domain-patterns.create');
    }

    public function store(Request $request)
    {
        $data = $this->validatedData($request);
        $data['created_by'] = $request->user('admin')?->id;
        $pattern = BlockedDomainPattern::create($data);

        $this->logCreated($pattern, "Blocked pattern '{$pattern->pattern}' added");

        return redirect()->route('admin.blocked-domain-patterns.index')
            ->with('success', __('admin/blocked-domain-patterns.created'));
    }

    public function edit(BlockedDomainPattern $blockedDomainPattern)
    {
        return view('admin.blocked-domain-patterns.edit', ['pattern' => $blockedDomainPattern]);
    }

    public function update(Request $request, BlockedDomainPattern $blockedDomainPattern)
    {
        $data = $this->validatedData($request, $blockedDomainPattern);
        $blockedDomainPattern->update($data);

        $this->logUpdated($blockedDomainPattern, "Blocked pattern '{$blockedDomainPattern->pattern}' updated");

        return redirect()->route('admin.blocked-domain-patterns.index')
            ->with('success', __('admin/blocked-domain-patterns.updated'));
    }

    public function destroy(BlockedDomainPattern $blockedDomainPattern)
    {
        $name = $blockedDomainPattern->pattern;
        $blockedDomainPattern->delete();

        $this->logDeleted($blockedDomainPattern, "Blocked pattern '{$name}' removed");

        return redirect()->route('admin.blocked-domain-patterns.index')
            ->with('success', __('admin/blocked-domain-patterns.deleted'));
    }

    private function validatedData(Request $request, ?BlockedDomainPattern $existing = null): array
    {
        $uniqueRule = 'unique:blocked_domain_patterns,pattern,'.($existing?->id ?? 'NULL').',id,match_type,'.$request->input('match_type');

        return $request->validate([
            'pattern' => ['required', 'string', 'max:255', $uniqueRule],
            'match_type' => 'required|in:'.implode(',', BlockedDomainPattern::ALL_TYPES),
            'reason' => 'nullable|string|max:1000',
            'is_active' => 'nullable|boolean',
        ]) + ['is_active' => $request->boolean('is_active', true)];
    }
}
