<?php
declare (strict_types=1);

namespace app\adminapi\service\message;

use app\common\model\sms\SmsTemplate;
use core\base\BaseService;

class SmsTemplateService extends BaseService
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new SmsTemplate();
    }

    public function getList(array $params = []): array
    {
        $query = $this->model->order('id', 'desc');

        if (!empty($params['template_key'])) {
            $query->whereLike('template_key', '%' . $params['template_key'] . '%');
        }
        if (!empty($params['template_name'])) {
            $query->whereLike('template_name', '%' . $params['template_name'] . '%');
        }

        return $this->pageQuery($query);
    }

    public function getDetail(int $id): ?array
    {
        $row = $this->model->find($id);
        return $row ? $row->toArray() : null;
    }

    public function create(array $data): bool
    {
        try {
            return (bool)$this->model->save($data);
        } catch (\Throwable $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public function update(int $id, array $data): bool
    {
        $row = $this->model->find($id);
        if (!$row) {
            self::setError('模板不存在');
            return false;
        }

        try {
            return (bool)$row->save($data);
        } catch (\Throwable $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public function delete(int $id): bool
    {
        return (bool)$this->model->destroy($id);
    }
}
