<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Branch;
use App\Models\Department;
use App\Services\Care\AuditLogger;
use App\Services\Care\CarePermissions;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DepartmentController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'admin.departments.view');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);
        $member = $this->member($request);
        $permissions = app(CarePermissions::class);

        $departments = Department::owned($owner)
            ->whereHas('branch', fn ($q) => $q->where('organization_id', $organization->id))
            ->with('branch')
            ->orderBy('name')
            ->get();

        $heroStats = [
            'total' => $departments->count(),
            'active' => $departments->where('is_active', true)->count(),
            'branches' => $departments->pluck('branch_id')->unique()->count(),
        ];

        return view('care.admin.departments.index', [
            'departments' => $departments,
            'organization' => $organization,
            'types' => config('care.department_types'),
            'heroStats' => $heroStats,
            'canManage' => $permissions->can($member, 'admin.departments.manage'),
        ]);
    }

    public function create(Request $request): View
    {
        $this->authorizeAbility($request, 'admin.departments.manage');
        $organization = $this->organization($request);

        $branches = Branch::owned($this->ownerRef($request))
            ->where('organization_id', $organization->id)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();

        return view('care.admin.departments.create', [
            'organization' => $organization,
            'branches' => $branches,
            'types' => config('care.department_types'),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'admin.departments.manage');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $validated = $request->validate([
            'branch_id' => ['required', 'integer', 'exists:care_branches,id'],
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'in:'.implode(',', array_keys(config('care.department_types')))],
        ]);

        $branch = Branch::owned($owner)->findOrFail($validated['branch_id']);
        abort_unless($branch->organization_id === $organization->id, 404);

        $department = Department::create([
            'owner_ref' => $owner,
            'branch_id' => $branch->id,
            'name' => $validated['name'],
            'type' => $validated['type'],
            'is_active' => true,
        ]);

        AuditLogger::record($owner, 'department.created', $organization->id, $owner, Department::class, $department->id);

        return redirect()->route('care.departments.index')->with('success', 'Department created.');
    }

    public function edit(Request $request, Department $department): View
    {
        $this->authorizeAbility($request, 'admin.departments.manage');
        $this->authorizeOwner($request, $department);

        return view('care.admin.departments.edit', [
            'department' => $department,
            'types' => config('care.department_types'),
        ]);
    }

    public function update(Request $request, Department $department): RedirectResponse
    {
        $this->authorizeAbility($request, 'admin.departments.manage');
        $this->authorizeOwner($request, $department);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'in:'.implode(',', array_keys(config('care.department_types')))],
            'is_active' => ['boolean'],
        ]);

        $department->update([
            ...$validated,
            'is_active' => $request->boolean('is_active', true),
        ]);

        AuditLogger::record(
            $this->ownerRef($request),
            'department.updated',
            $department->branch->organization_id,
            $this->ownerRef($request),
            Department::class,
            $department->id,
        );

        return redirect()->route('care.departments.index')->with('success', 'Department updated.');
    }

    public function destroy(Request $request, Department $department): RedirectResponse
    {
        $this->authorizeAbility($request, 'admin.departments.manage');
        $this->authorizeOwner($request, $department);

        $department->load('branch');
        $organizationId = $department->branch->organization_id;
        $departmentId = $department->id;

        $department->delete();

        AuditLogger::record(
            $this->ownerRef($request),
            'department.deleted',
            $organizationId,
            $this->ownerRef($request),
            Department::class,
            $departmentId,
        );

        return redirect()->route('care.departments.index')->with('success', 'Department removed.');
    }
}
