<?php

namespace App\Models;

use App\Core\Security;
use App\Core\Database;

/**
 * MetaSession Model
 * Handles the meta_sessions table with encryption for page_access_token.
 */
class MetaSession extends BaseModel
{
    protected static string $table = 'meta_sessions';

    /**
     * Get all connected Meta sessions for a company
     */
    public static function findAllByCompany(int $companyId): array
    {
        $sessions = Database::select(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id ASC",
            [$companyId]
        );

        foreach ($sessions as &$session) {
            $session['page_access_token'] = $session['page_access_token'] ? Security::decrypt($session['page_access_token']) : '';
        }

        return $sessions;
    }

    /**
     * Find a specific session by page_id and channel_type (messenger/instagram)
     */
    public static function findByPageId(string $pageId, string $channelType)
    {
        $session = Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE page_id = ? AND channel_type = ? LIMIT 1",
            [$pageId, $channelType]
        );

        if ($session) {
            $session['page_access_token'] = $session['page_access_token'] ? Security::decrypt($session['page_access_token']) : '';
        }

        return $session;
    }

    /**
     * Save/Connect Meta session
     */
    public static function connectSession(int $companyId, string $channelType, string $pageId, string $pageName, string $pageAccessToken): int
    {
        $existing = Database::selectOne(
            "SELECT id FROM " . static::$table . " WHERE page_id = ? AND channel_type = ? LIMIT 1",
            [$pageId, $channelType]
        );

        $encryptedToken = Security::encrypt($pageAccessToken);

        if ($existing) {
            static::update($existing['id'], [
                'company_id' => $companyId,
                'page_name' => $pageName,
                'page_access_token' => $encryptedToken,
                'status' => 'connected'
            ]);
            return (int)$existing['id'];
        } else {
            return (int)static::create([
                'company_id' => $companyId,
                'channel_type' => $channelType,
                'page_id' => $pageId,
                'page_name' => $pageName,
                'page_access_token' => $encryptedToken,
                'status' => 'connected'
            ]);
        }
    }
}
