<?php

namespace App\Models;

use App\Core\Database;

/**
 * CompanyEndpoint Model
 * Handles configuration of dynamic integration endpoints for multi-tenant SaaS integration.
 */
class CompanyEndpoint extends BaseModel
{
    protected static string $table = 'company_endpoints';

    /**
     * Find all endpoints for a company
     */
    public static function findAllByCompany(int $companyId): array
    {
        self::ensureTableExists();
        return Database::select(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id DESC",
            [$companyId]
        );
    }

    /**
     * Find a specific endpoint by action type for a company
     */
    public static function findByAction(int $companyId, string $actionType): ?array
    {
        self::ensureTableExists();
        return Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? AND action_type = ? LIMIT 1",
            [$companyId, $actionType]
        );
    }

    /**
     * Save or update an endpoint configuration
     */
    public static function saveSecure(array $data)
    {
        self::ensureTableExists();

        if (isset($data['id'])) {
            $id = $data['id'];
            unset($data['id']);
            self::update($id, $data);
            return $id;
        } else {
            return self::create($data);
        }
    }

    /**
     * Ensure the table exists dynamically
     */
    public static function ensureTableExists(): void
    {
        static $checked = false;
        if ($checked) return;
        try {
            Database::execute("
                CREATE TABLE IF NOT EXISTS `company_endpoints` (
                    `id` INT AUTO_INCREMENT PRIMARY KEY,
                    `company_id` INT NOT NULL,
                    `name` VARCHAR(255) NOT NULL,
                    `endpoint_url` VARCHAR(512) NOT NULL,
                    `action_type` VARCHAR(100) NOT NULL,
                    `description` TEXT NULL,
                    `api_key` VARCHAR(255) NULL,
                    `headers` TEXT NULL,
                    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX `idx_endpoint_company` (`company_id`),
                    INDEX `idx_endpoint_action` (`action_type`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            ");
            
            // Auto-migration: check if api_key column exists, if not, add it
            try {
                Database::execute("SELECT `api_key` FROM `company_endpoints` LIMIT 1");
            } catch (\Exception $colException) {
                Database::execute("ALTER TABLE `company_endpoints` ADD COLUMN `api_key` VARCHAR(255) NULL AFTER `description`");
            }

            $checked = true;
        } catch (\Exception $e) {
            error_log("Failed to ensure company_endpoints table: " . $e->getMessage());
        }
    }
}
