<?php

namespace App\Http\Controllers\Admin\Office;

use App\Http\Controllers\Controller;
use App\Models\Office\Announcement;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AnnouncementController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Announcement::query()->with('author');
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('publish_status'), fn($q) => $q->where('publish_status', $request->publish_status));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'type' => 'sometimes|integer|in:1,2,3',
            'is_top' => 'sometimes|boolean',
        ]);
        $validated['author_id'] = auth()->id();

        return $this->success(Announcement::create($validated));
    }

    public function show(Announcement $announcement): JsonResponse
    {
        return $this->success($announcement->load('author'));
    }

    public function update(Request $request, Announcement $announcement): JsonResponse
    {
        $validated = $request->validate([
            'title' => 'sometimes|string|max:255',
            'content' => 'sometimes|string',
            'type' => 'sometimes|integer|in:1,2,3',
            'is_top' => 'sometimes|boolean',
        ]);
        $announcement->update($validated);

        return $this->success($announcement);
    }

    public function destroy(Announcement $announcement): JsonResponse
    {
        $announcement->delete();
        return $this->success(null);
    }

    public function publish(Announcement $announcement): JsonResponse
    {
        if ($announcement->publish_status === 1) {
            return $this->error('该公告已发布', 40001);
        }
        $announcement->update([
            'publish_status' => 1,
            'published_at' => now(),
        ]);

        return $this->success($announcement);
    }
}
