<?php

namespace App\Controllers;

use App\Traits\ResponseTrait;
use CodeIgniter\Controller;

class EdgeController extends Controller
{
    use ResponseTrait;

    protected $db;
    protected $edgeResModel;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
        $this->edgeResModel = new \App\Models\EdgeResModel();
    }

    /**
     * POST /api/edge/result
     * Receive results from tiny-edge
     */
    public function results()
    {
        try {
            $input = $this->request->getJSON(true);

            if (empty($input)) {
                return $this->failValidationErrors('Invalid JSON payload');
            }

            // Extract key fields from payload
            $sampleId = $input['sample_id'] ?? null;
            $instrumentId = $input['instrument_id'] ?? null;
            $patientId = $input['patient_id'] ?? null;

            // Store in edgeres table
            $data = [
                'SiteID' => 1, // Default site, can be configured
                'InstrumentID' => $instrumentId,
                'SampleID' => $sampleId,
                'PatientID' => $patientId,
                'Payload' => json_encode($input),
                'Status' => 'pending',
                'AutoProcess' => 0, // Default to manual processing
                'CreateDate' => date('Y-m-d H:i:s')
            ];

            $id = $this->edgeResModel->insert($data);

            if (!$id) {
                return $this->failServerError('Failed to save result');
            }

            return $this->respondCreated([
                'status' => 'success',
                'message' => 'Result received and queued',
                'data' => [
                    'edge_res_id' => $id,
                    'sample_id' => $sampleId,
                    'instrument_id' => $instrumentId
                ]
            ]);

        } catch (\Throwable $e) {
            return $this->failServerError('Error processing result: ' . $e->getMessage());
        }
    }

    /**
     * GET /api/edge/order
     * Return pending orders for an instrument
     */
    public function orders()
    {
        try {
            $instrumentId = $this->request->getGet('instrument');

            if (!$instrumentId) {
                return $this->failValidationErrors('instrument parameter is required');
            }

            // TODO: Implement order fetching logic
            // For now, return empty array
            return $this->respond([
                'status' => 'success',
                'message' => 'Orders fetched',
                'data' => []
            ]);

        } catch (\Throwable $e) {
            return $this->failServerError('Error fetching orders: ' . $e->getMessage());
        }
    }

    /**
     * POST /api/edge/order/:id/ack
     * Acknowledge order delivery
     */
    public function ack($orderId = null)
    {
        try {
            if (!$orderId) {
                return $this->failValidationErrors('Order ID is required');
            }

            $input = $this->request->getJSON(true);
            $instrumentId = $input['instrument_id'] ?? null;

            // Log acknowledgment
            $this->db->table('edgeack')->insert([
                'OrderID' => $orderId,
                'InstrumentID' => $instrumentId,
                'AckDate' => date('Y-m-d H:i:s'),
                'CreateDate' => date('Y-m-d H:i:s')
            ]);

            return $this->respond([
                'status' => 'success',
                'message' => 'Order acknowledged',
                'data' => [
                    'order_id' => $orderId
                ]
            ]);

        } catch (\Throwable $e) {
            return $this->failServerError('Error acknowledging order: ' . $e->getMessage());
        }
    }

    /**
     * POST /api/edge/status
     * Log instrument status
     */
    public function status()
    {
        try {
            $input = $this->request->getJSON(true);

            $instrumentId = $input['instrument_id'] ?? null;
            $status = $input['status'] ?? null;
            $lastActivity = $input['last_activity'] ?? null;
            $timestamp = $input['timestamp'] ?? date('Y-m-d H:i:s');

            if (!$instrumentId || !$status) {
                return $this->failValidationErrors('instrument_id and status are required');
            }

            // Store status log
            $this->db->table('edgestatus')->insert([
                'InstrumentID' => $instrumentId,
                'Status' => $status,
                'LastActivity' => $lastActivity,
                'Timestamp' => $timestamp,
                'CreateDate' => date('Y-m-d H:i:s')
            ]);

            return $this->respond([
                'status' => 'success',
                'message' => 'Status logged'
            ]);

        } catch (\Throwable $e) {
            return $this->failServerError('Error logging status: ' . $e->getMessage());
        }
    }
}
