<?php

namespace App\Models;

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

/**
 * WooCommerceStore Model
 * Represents WooCommerce connections per company. Keys are encrypted.
 */
class WooCommerceStore extends BaseModel
{
    protected static string $table = 'woocommerce_stores';

    /**
     * Find store connection by company ID
     */
    public static function findByCompany(int $companyId): ?array
    {
        return Database::selectOne(
            "SELECT * FROM " . static::$table . " WHERE company_id = ? LIMIT 1",
            [$companyId]
        );
    }

    /**
     * Get decrypted credentials for API calls
     */
    public static function getDecryptedCredentials(array $store): array
    {
        return [
            'store_url' => $store['store_url'],
            'consumer_key' => Security::decrypt($store['consumer_key']),
            'consumer_secret' => Security::decrypt($store['consumer_secret']),
            'webhook_secret' => $store['webhook_secret'] ?? null
        ];
    }

    /**
     * Save or update WooCommerce connection
     */
    public static function saveStore(int $companyId, string $storeUrl, string $consumerKey, string $consumerSecret, ?string $webhookSecret = null): string
    {
        $encryptedKey = Security::encrypt($consumerKey);
        $encryptedSecret = Security::encrypt($consumerSecret);

        $existing = self::findByCompany($companyId);
        $data = [
            'company_id' => $companyId,
            'store_url' => rtrim($storeUrl, '/'),
            'consumer_key' => $encryptedKey,
            'consumer_secret' => $encryptedSecret,
            'webhook_secret' => $webhookSecret
        ];

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

    /**
     * Delete WooCommerce connection
     */
    public static function deleteByCompany(int $companyId): int
    {
        return Database::execute(
            "DELETE FROM " . static::$table . " WHERE company_id = ?",
            [$companyId]
        );
    }
}
