<?php

namespace App\Development\Reporting;

use Carbon\Carbon;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;

// Reporting microservice mock (App\Repositories\ReportRepository). Each endpoint is served from a
// JSON scenario file under Development/Reporting; the manifest maps each URL straight to a method.
class Routes
{
    // GET /creatia-report/destination-table
    public function destination_table(array $params, Request $request)
    {
        $organisation = $request->data()['filters']['organisation_id'] ?? 'Admin';

        if(array_search($organisation, [ 1, 2, 3, 4, 'Admin' ]) === false) {
            $organisation = 'Invalid';
        }

        $data = json_decode(file_get_contents(app_path("Development/Reporting/Tables/OrganisationReports-$organisation.json")), true);
        $data['draw'] = (int) $request['draw'];

        return Http::response(json_encode($data), 200);
    }

    // GET /creatia-report/automation-destination-table
    public function automation_table(array $params, Request $request)
    {
        // Draw 2 is a fixed scenario whose attacks sit at set offsets from now (asserted by tests),
        // so the stored rows carry a minutes-ago offset that we resolve against the current time.
        if((int) $request['draw'] === 2) {
            $rows = json_decode(file_get_contents(app_path('Development/Reporting/Tables/OrganisationReports-Automation-2.json')), true);

            foreach($rows as &$row) {
                $finish = Carbon::now()->subMinutes($row['finish_minutes_ago']);
                $row['start_at'] = $finish->copy()->subMinutes(10);
                $row['finish_at'] = $finish;
                unset($row['finish_minutes_ago']);
            }
            unset($row);

            return Http::response(json_encode([ 'draw' => 2, 'data' => $rows, 'recordsFiltered' => sizeof($rows), 'recordsTotal' => sizeof($rows) ]), 200);
        }

        $data = json_decode(file_get_contents(app_path('Development/Reporting/Tables/OrganisationReports-Automation.json')), true);
        $data['draw'] = (int) $request['draw'];

        return Http::response(json_encode($data), 200);
    }

    // GET /creatia-report/leaderboard
    public function leaderboard(array $params, Request $request)
    {
        $data = json_decode(file_get_contents(app_path('Models/ReportListTest.json')), true);
        $data['draw'] = (int) $request['draw'];

        return Http::response(json_encode($data), 200);
    }

    // GET /creatia-report/destination-report - report download, plus a validate path.
    public function report(array $params, Request $request)
    {
        $report_id = (int) ($request->data()['report_id'] / 10);

        if(isset($request->data()['validate'])) {
            $user = Auth::user();
            $organisation_id = $user !== null ? $user->organisation_id : 'Admin';

            $rows = json_decode(file_get_contents(app_path("Development/Reporting/Tables/OrganisationReports-$organisation_id.json")), true);

            foreach($rows['data'] as $row) {
                if($row['report_id'] == $request->data()['report_id']) {
                    return Http::response([
                        'valid'         => true,
                        'destination'   => $row['destination'],
                        'start'         => $row['start_at'],
                        'finish'        => $row['finish_at'],
                        'subtenant_ids' => $row['organisation_id'] == 1 ? [1, 4] : [$row['organisation_id']]
                    ]);
                }
            }

            return Http::response([ 'valid' => false ]);
        }

        if((isset($request->data()['organisation_id']) && $report_id !== $request->data()['organisation_id']) && !(Auth::user()->organisation_id == 4 && $report_id == 1)) {
            return Http::response(file_get_contents(app_path('Development/Reporting/Reports/OrganisationReport-Invalid.json')), 400);
        }

        if($report_id == 4 && $report_id != 1) {
            return Http::response([ 'error' => 'Invalid request' ], 400);
        }

        return Http::response(file_get_contents(app_path("Development/Reporting/Reports/OrganisationReport-$report_id.pdf")), 200);
    }

    // GET /creatia-notification/start - attack start sizes, keyed by destination address.
    public function notification(array $params, Request $request)
    {
        $scenarios = json_decode(file_get_contents(app_path('Development/Reporting/Notification.json')), true);
        $address = $request->data()['address'] ?? null;

        if(!isset($scenarios[$address])) {
            return Http::response([ 'Fallback Error' ], 500);
        }

        return Http::response($scenarios[$address]['body'], $scenarios[$address]['status']);
    }
}
