<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Models\CompanyEndpoint;

class EndpointController extends BaseController
{
    /**
     * List all custom API endpoints for the company
     */
    public function index(Request $request, Response $response)
    {
        $endpoints = CompanyEndpoint::findAllByCompany($request->company_id);
        $response->json([
            'status' => 'success',
            'data' => $endpoints
        ]);
    }

    /**
     * Create or update a custom API endpoint configuration
     */
    public function store(Request $request, Response $response)
    {
        $errors = $this->validate($request, [
            'name' => 'required',
            'endpoint_url' => 'required',
            'action_type' => 'required'
        ]);

        if (!empty($errors)) {
            $response->status(400)->json(['status' => 'error', 'errors' => $errors]);
            return;
        }

        $body = $request->getBody();
        $saveData = [
            'company_id' => $request->company_id,
            'name' => $body['name'],
            'endpoint_url' => $body['endpoint_url'],
            'action_type' => $body['action_type'],
            'description' => $body['description'] ?? null,
            'api_key' => $body['api_key'] ?? null,
            'headers' => $body['headers'] ?? null
        ];

        if (isset($body['id'])) {
            $saveData['id'] = (int)$body['id'];
        }

        $id = CompanyEndpoint::saveSecure($saveData);

        $response->json([
            'status' => 'success',
            'message' => 'Integration endpoint saved successfully',
            'id' => $id
        ]);
    }

    /**
     * Delete an API endpoint configuration
     */
    public function delete(Request $request, Response $response)
    {
        $body = $request->getBody();
        if (empty($body['id'])) {
            $response->status(400)->json(['status' => 'error', 'message' => 'Missing endpoint ID']);
            return;
        }

        // Verify ownership
        $endpoint = CompanyEndpoint::find($body['id']);
        if (!$endpoint || $endpoint['company_id'] !== $request->company_id) {
            $response->status(404)->json(['status' => 'error', 'message' => 'Endpoint not found']);
            return;
        }

        CompanyEndpoint::delete($body['id']);

        $response->json([
            'status' => 'success',
            'message' => 'Integration endpoint deleted successfully'
        ]);
    }
}
