<?php

namespace App\Services;

use App\Models\ActivityLog;
use App\Models\SmsGateway;
use App\Repositories\SmsGatewayRepository;
use Illuminate\Support\Facades\DB;

class SmsGatewayService
{
    public function __construct(protected SmsGatewayRepository $repository) {}

    public function create(array $data): SmsGateway
    {
        if (! empty($data['settings']) && is_string($data['settings'])) {
            $data['settings'] = json_decode($data['settings'], true) ?: [];
        }

        $gateway = DB::transaction(function () use ($data) {
            if (! empty($data['status'])) SmsGateway::query()->update(['status' => false]);
            return $this->repository->create($data);
        });

        ActivityLog::create([
            'user_id' => auth()->id(),
            'action' => 'sms_gateway_created',
            'resource_type' => SmsGateway::class,
            'resource_id' => $gateway->id,
            'description' => 'SMS gateway created: '.$gateway->name,
        ]);

        return $gateway;
    }

    public function update(SmsGateway $gateway, array $data): bool
    {
        if (! empty($data['settings']) && is_string($data['settings'])) {
            $data['settings'] = json_decode($data['settings'], true) ?: [];
        }

        if (blank($data['api_key'] ?? null)) unset($data['api_key']);
        $result = DB::transaction(function () use ($gateway, $data) {
            if (! empty($data['status'])) SmsGateway::where('id', '<>', $gateway->id)->update(['status' => false]);
            return $this->repository->update($gateway, $data);
        });

        ActivityLog::create([
            'user_id' => auth()->id(),
            'action' => 'sms_gateway_updated',
            'resource_type' => SmsGateway::class,
            'resource_id' => $gateway->id,
            'description' => 'SMS gateway updated: '.$gateway->name,
        ]);

        return $result;
    }

    public function delete(SmsGateway $gateway): bool
    {
        $result = $this->repository->delete($gateway);

        ActivityLog::create([
            'user_id' => auth()->id(),
            'action' => 'sms_gateway_deleted',
            'resource_type' => SmsGateway::class,
            'resource_id' => $gateway->id,
            'description' => 'SMS gateway deleted: '.$gateway->name,
        ]);

        return $result;
    }
}
