<?php
// app/Services/RequirementOperationService.php

namespace App\Services;

use App\Models\Project;
use App\Models\UserOperation;
use App\Models\Requirement;
use App\Models\NonFunctionalRequirement;
use App\Models\RequirementOperation;
use Illuminate\Support\Facades\DB;

class RequirementOperationService
{
    /**
     * Generate requirement operations for all users in a project when status changes to voting
     * First deletes all existing records for the project, then generates new ones
     */
    public function generateVotingOperations(Project $project): array
    {
        // Use transaction to ensure data consistency
        return DB::transaction(function () use ($project) {
            try {
                // 1. Delete all existing requirement operations for this project
                $deletedCount = RequirementOperation::where('project_id', $project->id)->delete();
                
                // 2. Get all user operations for this project
                $userOperations = $project->userOperations()->with('user')->get();
                
                $totalGenerated = 0;
                
                // 3. Generate new operations for each user
                foreach ($userOperations as $userOperation) {
                    $generatedCount = $this->generateForUserOperation($userOperation);
                    $totalGenerated += $generatedCount;
                }
                
                return [
                    'success' => true,
                    'message' => "Voting operations generated. Deleted: {$deletedCount} records, Generated: {$totalGenerated} new records.",
                    'deleted_count' => $deletedCount,
                    'generated_count' => $totalGenerated
                ];
                
            } catch (\Exception $e) {
                return [
                    'success' => false,
                    'message' => 'Failed to generate voting operations: ' . $e->getMessage()
                ];
            }
        });
    }

    /**
     * Generate requirement operations for a specific user operation
     * Returns the number of operations generated
     */
    public function generateForUserOperation(UserOperation $userOperation): int
    {
        $requirementOperations = $this->generateRequirementOperations($userOperation);
        
        if (!empty($requirementOperations)) {
            RequirementOperation::insert($requirementOperations);
            return count($requirementOperations);
        }
        
        return 0;
    }

    /**
     * Generate the requirement operations data
     */
    protected function generateRequirementOperations(UserOperation $userOperation): array
    {
        $user = $userOperation->user;
        $projectId = $userOperation->project_id;

        // Load requirements and NFRs
        $requirements = Requirement::where('project_id', $projectId)->get();
        $nfrs = NonFunctionalRequirement::where('project_id', $projectId)->get();

        // If no requirements or NFRs, return empty array
        if ($requirements->isEmpty() || $nfrs->isEmpty()) {
            return [];
        }

        $now = now();
        $rows = [];

        foreach ($requirements as $requirement) {
            foreach ($nfrs as $nfr) {
                $rows[] = [
                    'user_id' => $user->id,
                    'r_id' => $requirement->id,
                    'nfu_id' => $nfr->id,
                    'project_id' => $projectId,
                    'nfu_value' => 0.00,
                    'status' => 'pending',
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
            }
        }

        return $rows;
    }
}