<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\JobPosting;
use App\Services\Recruitment\RecruitmentHomeService;
use App\Support\FormTextRules;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class JobPostingController extends Controller
{
    public function __construct(
        protected RecruitmentHomeService $home
    ) {}

    public function index(Request $request)
    {
        $status = (string) $request->query('status', '');

        $jobPostings = JobPosting::with('department')
            ->withCount([
                'applicants',
                'applicants as referrals_count' => fn ($q) => $q->where('source', 'referral'),
            ])
            ->when(in_array($status, ['active', 'closed'], true), fn ($q) => $q->where('status', $status))
            ->latest()
            ->paginate(12)
            ->withQueryString();

        $pipelineByJob = [];
        foreach ($jobPostings as $job) {
            $pipelineByJob[$job->id] = $this->home->jobPipelineCounts($job);
        }

        $activeCount = JobPosting::where('status', 'active')->count();
        $closedCount = JobPosting::where('status', 'closed')->count();

        return view('recruitment.job-postings.index', compact(
            'jobPostings',
            'activeCount',
            'closedCount',
            'status',
            'pipelineByJob'
        ));
    }

    public function create()
    {
        $departments = Department::orderBy('name')->get();
        return view('recruitment.job-postings.create', compact('departments'));
    }

    public function store(Request $request)
    {
        $companyId = Auth::user()?->company_id;
        $validated = $request->validate($this->jobPostingRules(), FormTextRules::messages());

        JobPosting::create(array_merge($validated, [
            'company_id' => $companyId,
        ]));

        return redirect()->route('job-postings.index')->with('success', 'Job posting created successfully.');
    }

    public function edit(JobPosting $jobPosting)
    {
        $departments = Department::orderBy('name')->get();
        return view('recruitment.job-postings.edit', compact('jobPosting', 'departments'));
    }

    public function update(Request $request, JobPosting $jobPosting)
    {
        $validated = $request->validate($this->jobPostingRules(), FormTextRules::messages());

        $jobPosting->update($validated);

        return redirect()->route('job-postings.index')->with('success', 'Job posting updated successfully.');
    }

    public function destroy(JobPosting $jobPosting)
    {
        $jobPosting->delete();

        return redirect()->route('job-postings.index')->with('success', 'Job posting deleted successfully.');
    }

    /**
     * @return array<string, mixed>
     */
    protected function jobPostingRules(): array
    {
        return [
            'title' => FormTextRules::notNumericOnly(true, 191),
            'department_id' => ['required', 'exists:departments,id'],
            'location' => FormTextRules::notNumericOnly(false, 191),
            'employment_type' => ['required', 'string', 'max:50'],
            'openings' => ['required', 'integer', 'min:1'],
            'status' => ['required', Rule::in(['active', 'closed'])],
            'posted_at' => ['nullable', 'date'],
            'description' => FormTextRules::notNumericOnly(false, 5000),
        ];
    }
}
