<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SlackNotifierService
{
    protected array $webhooks = [];

    public function __construct()
    {
        $this->webhooks = [
            'orders' => config('slack.webhooks.orders'),
            'design' => config('slack.webhooks.design'),
            'production' => config('slack.webhooks.production'),
            'shipping' => config('slack.webhooks.shipping'),
            'ops_alerts' => config('slack.webhooks.ops_alerts'),
        ];
    }

    /**
     * Send notification to #orders channel
     */
    public function orders(string $message, array $blocks = []): void
    {
        $this->send($this->webhooks['orders'], $message, $blocks);
    }

    /**
     * Send notification to #design channel
     */
    public function design(string $message, array $blocks = []): void
    {
        $this->send($this->webhooks['design'], $message, $blocks);
    }

    /**
     * Send notification to #production channel
     */
    public function production(string $message, array $blocks = []): void
    {
        $this->send($this->webhooks['production'], $message, $blocks);
    }

    /**
     * Send notification to #shipping channel
     */
    public function shipping(string $message, array $blocks = []): void
    {
        $this->send($this->webhooks['shipping'], $message, $blocks);
    }

    /**
     * Send notification to #ops-alerts channel
     */
    public function opsAlerts(string $message, array $blocks = []): void
    {
        $this->send($this->webhooks['ops_alerts'], $message, $blocks);
    }

    /**
     * Send payload to Slack webhook
     */
    protected function send(string $webhook, string $message, array $blocks = []): void
    {
        if (! $webhook) {
            Log::warning('Slack webhook not configured for channel', ['message' => $message]);

            return;
        }

        try {
            $payload = ['text' => $message];

            if (! empty($blocks)) {
                $payload['blocks'] = $blocks;
            }

            Http::post($webhook, $payload);
        } catch (\Exception $e) {
            Log::error('Failed to send Slack notification', [
                'webhook' => substr($webhook, 0, 20).'...',
                'message' => $message,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
