<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Models\Sprint;
use App\Models\Project;
use App\Models\ProjectSprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\ProjectResource;
use App\Models\NonFunctionalRequirement;
use App\Http\Requests\StoreProjectRequest;
use App\Http\Controllers\ProjectController;
use App\Http\Requests\UpdateProjectRequest;
use App\Services\RequirementOperationService;

class ProjectController extends Controller
{

    protected $requirementOperationService;

    public function __construct(RequirementOperationService $requirementOperationService)
    {
        $this->requirementOperationService = $requirementOperationService;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = Auth::user();

        $projectsQuery = Project::query();

        if ($user->role !== 'admin') {
            // Normal users only see projects they’re assigned to
            $projectsQuery->whereHas('users', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            });
        }

        return Inertia::render('projects/Index', [
            'projects' => ProjectResource::collection(
                $projectsQuery->paginate(10)
            ),
            'breadcrumbs' => [
                [ 'title' => 'Project Management', 'href' => '/project-management' ],
            ],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        return Inertia::render('projects/Project-create', [
            'breadcrumbs' => [
                [ 'title' => 'Project Management', 'href' => '/project-management' ],
                [ 'title' => 'Project Management', 'href' => '/project-management/project-create' ],
            ],
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreProjectRequest $request)
    {
        DB::transaction(function () use ($request) {
            // 1. Create the project
            $project = Project::create([
                'name' => $request->name,
                'description' => $request->description,
                'status' => 'requirement change',
            ]);

            // 2. Attach sprints (first N, all pending)
            $pivotData = Sprint::orderBy('id')
                ->take($request->sprint)
                ->pluck('id')
                ->mapWithKeys(fn ($id) => [$id => ['status' => ProjectSprint::STATUS_PENDING]])
                ->toArray();

            $project->sprints()->attach($pivotData);

            // 3. Attach fixed Non-Functional Requirements (all with weight = 0)
            foreach (NonFunctionalRequirement::types() as $nfrType) {
                $project->nonFunctionalRequirements()->create([
                    'name'        => $nfrType['name'],
                    'description' => $nfrType['description'],
                    'weight'      => 0.00,
                ]);
            }
        });

        return redirect()
            ->route('project.index')
            ->with('success');
    }

    /**
     * Display the specified resource.
     */
    public function show(Project $project)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Project $project)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateProjectRequest $request, string $id)
    {
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $project = Project::findOrFail($id);
        
        // Store the original status before update
        $originalStatus = $project->status;

        $project->update([
            'name' => $request->name,
            'description' => $request->description,
            'status' => $request->status,
        ]);

        // Check if status changed to voting
        if ($originalStatus == 'requirement change' && $project->status === 'voting') {

            $result = $this->requirementOperationService->generateVotingOperations($project);
            
            if ($result['success']) {
                return redirect()
                    ->back()
                    ->with('success', 'Project updated successfully. ' . $result['message']);
            } else {
                return redirect()
                    ->back()
                    ->with('error', 'Project updated but failed to generate voting operations: ' . $result['message']);
            }
        }

        return redirect()
            ->back()
            ->with('success', 'Project updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized');
        }

        $project = Project::findOrFail($id);

        $project->delete();

        return redirect()->back()->with('success', 'Project deleted successfully.');
    }
}
