<?php

namespace App\Services;

use App\Http\Responses\ApiResponse;
use App\Models\ContentModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class ContentModelService
{
    public function index(array $params): array
    {
        $query = ContentModel::withCount(['fields', 'categories'])
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc');

        if (! empty($params['keyword'])) {
            $query->where(function ($q) use ($params) {
                $q->where('name', 'like', "%{$params['keyword']}%")
                    ->orWhere('alias', 'like', "%{$params['keyword']}%");
            });
        }

        if (! empty($params['alias'])) {
            $query->where('alias', $params['alias']);
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        $perPage = $params['per_page'] ?? 15;
        $paginator = $query->paginate($perPage);

        return ApiResponse::paginate($paginator);
    }

    public function store(array $data): array
    {
        if (ContentModel::where('alias', $data['alias'])->exists()) {
            return ApiResponse::error(40201, '模型别名已存在');
        }

        $tableName = $data['table_name'] ?? ('content_'.$data['alias']);

        $this->createExtensionTable($tableName);

        $model = ContentModel::create([
            'name' => $data['name'],
            'alias' => $data['alias'],
            'description' => $data['description'] ?? null,
            'table_name' => $tableName,
            'sort' => $data['sort'] ?? 0,
            'status' => $data['status'] ?? 1,
        ]);

        return ApiResponse::success($model, '创建成功');
    }

    public function show(int $id): array
    {
        $model = ContentModel::with('fields')->find($id);

        if (! $model) {
            return ApiResponse::error(40201, '模型不存在');
        }

        return ApiResponse::success($model);
    }

    public function update(int $id, array $data): array
    {
        $model = ContentModel::find($id);

        if (! $model) {
            return ApiResponse::error(40201, '模型不存在');
        }

        $updateData = array_filter([
            'name' => $data['name'] ?? null,
            'description' => $data['description'] ?? null,
            'sort' => $data['sort'] ?? null,
            'status' => $data['status'] ?? null,
            'field_config' => $data['field_config'] ?? null,
        ], fn ($value) => $value !== null);

        $model->update($updateData);

        return ApiResponse::success($model, '更新成功');
    }

    public function destroy(int $id): array
    {
        $model = ContentModel::find($id);

        if (! $model) {
            return ApiResponse::error(40201, '模型不存在');
        }

        if ($model->is_default) {
            return ApiResponse::error(40204, '默认模型不可删除');
        }

        if ($model->categories()->exists()) {
            return ApiResponse::error(40202, '该模型下存在关联分类，不可删除');
        }

        if ($model->contents()->exists()) {
            return ApiResponse::error(40203, '该模型下存在关联内容，不可删除');
        }

        DB::transaction(function () use ($model) {
            $model->fields()->delete();
            $model->categories()->update(['model_id' => null]);
            $model->delete();
        });

        $this->dropExtensionTable($model->table_name);

        return ApiResponse::success(null, '删除成功');
    }

    public function updateStatus(int $id, int $status): array
    {
        $model = ContentModel::find($id);

        if (! $model) {
            return ApiResponse::error(40201, '模型不存在');
        }

        $model->update(['status' => $status]);

        return ApiResponse::success($model, $status === 1 ? '启用成功' : '禁用成功');
    }

    public function saveSort(array $ids, array $sorts): array
    {
        foreach ($ids as $index => $id) {
            ContentModel::where('id', $id)->update([
                'sort' => isset($sorts[$index]) ? intval($sorts[$index]) : 0,
            ]);
        }

        return ApiResponse::success(null, '排序保存成功');
    }

    protected function createExtensionTable(string $tableName): void
    {
        if (Schema::hasTable($tableName)) {
            return;
        }

        Schema::create($tableName, function ($table) {
            $table->bigIncrements('id');
            $table->timestamp('create_time')->nullable();
            $table->timestamp('update_time')->nullable();
        });
    }

    protected function dropExtensionTable(string $tableName): void
    {
        if (Schema::hasTable($tableName)) {
            Schema::dropIfExists($tableName);
        }
    }
}
