<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Traits\AnalyzeData;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use Illuminate\Http\Request;
use Modules\Admin\app\Models\Sprint;
use Modules\Admin\app\Models\TestCaseForSprint;

class TestCaseForSprintController extends Controller
{
    use HasOrderByRequest;
    use HasFilterRequest;
    use HasSearchRequest;
    use AnalyzeData;

    public function getAllReportsForSprint($sprintId)
    {
        $testReports = TestCaseForSprint::where('sprint_id', $sprintId)->get();
        return AbstractController::ResultSuccess($testReports);
    }

    public function createTestReport(Request $request, $sprintId)
    {
        $user = auth('admins')->user();

        $request->validate([
            'name' => 'required|string|max:255',
            'position' => 'required|string',
            'input' => 'required|string',
            'expect_output' => 'required|string',
            'actual_output' => 'required|string',
            'note' => 'nullable|string',
            'issue_id_on_jira' => 'nullable|string',
            'bug_id_on_jira' => 'nullable|string',
        ]);

        $sprint = Sprint::find($sprintId);
        if (!$sprint) {
            // Create new sprint
            Sprint::create([
                'id' => $sprintId,
                'name' => $request->sprint_name,
                'project_id' => $request->project_id,
                'point' => "",
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'complete_date' => $request->complete_date,
            ]);
        }

        $testReport = TestCaseForSprint::create([
            'name' => $request->name,
            'position' => $request->position,
            'input' => $request->input,
            'expect_output' => $request->expect_output,
            'actual_output' => $request->actual_output,
            'note' => $request->note,
            'issue_id_on_jira' => $request->issue_id_on_jira,
            'bug_id_on_jira' => $request->bug_id_on_jira,
            'sprint_id' => $sprintId,
            'created_by' => $user->name,
        ]);
        return AbstractController::ResultSuccess($testReport);
    }

    public function deleteTestReport(Request $request)
    {
        $id = $request->input('id');

        $testReport = TestCaseForSprint::find($id);

        if (!$testReport) {
            return AbstractController::ResultError("Test report not found", [], 404);
        }

        $testReport->delete();
        return AbstractController::ResultSuccess("Test report deleted successfully");
    }
}
