<?php

declare(strict_types=1);

namespace Kylin\Medical\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Medical\Services\MedicalService;

/**
 * 医疗管理控制器
 *
 * 提供预约挂号、退号、处方开具、药师审核、电子病历签名等 HTTP 接口。
 *
 * 法律合规：
 *  - 所有写操作通过 MedicalService 执行，自动记录审计日志
 *  - 病历查阅需权限校验（依据《医疗机构病历管理规定》第二十八条）
 */
class MedicalController extends BaseController
{
    public function __construct(private readonly MedicalService $service) {}

    /**
     * 创建预约挂号
     */
    public function createAppointment(Request $request): JsonResponse
    {
        $data = $request->validate([
            'patient_id' => 'required|integer',
            'doctor_id' => 'required|integer',
            'schedule_id' => 'required|integer',
        ]);

        $appointment = $this->service->createAppointment($data);
        return ApiResponse::success($appointment, '挂号成功');
    }

    /**
     * 退号
     */
    public function cancelAppointment(Request $request, int $id): JsonResponse
    {
        $request->validate(['reason' => 'nullable|string|max:500']);

        $appointment = $this->service->cancelAppointment($id, (string) ($request->input('reason', '')));
        return ApiResponse::success($appointment, '退号成功');
    }

    /**
     * 开具处方
     */
    public function createPrescription(Request $request): JsonResponse
    {
        $data = $request->validate([
            'medical_record_id' => 'required|integer',
            'doctor_id' => 'required|integer',
            'type' => 'nullable|string|in:normal,emergency',
            'items' => 'required|array|min:1|max:5',
            'items.*.drug_id' => 'required|integer',
            'items.*.dosage' => 'required|string|max:50',
            'items.*.frequency' => 'required|string|max:50',
            'items.*.days' => 'required|integer|min:1',
            'items.*.usage_method' => 'nullable|string|max:50',
            'items.*.remark' => 'nullable|string|max:500',
        ]);

        $prescription = $this->service->createPrescription($data);
        return ApiResponse::success($prescription, '处方开具成功');
    }

    /**
     * 药师审核处方
     */
    public function reviewPrescription(Request $request, int $id): JsonResponse
    {
        $data = $request->validate([
            'pharmacist_id' => 'required|integer',
            'approved' => 'required|boolean',
            'reason' => 'nullable|string|max:500',
        ]);

        $prescription = $this->service->reviewPrescription(
            $id,
            (int) $data['pharmacist_id'],
            (bool) $data['approved'],
            (string) ($data['reason'] ?? '')
        );
        return ApiResponse::success($prescription, $data['approved'] ? '审核通过' : '已退回');
    }

    /**
     * 电子病历签名
     */
    public function signMedicalRecord(Request $request, int $id): JsonResponse
    {
        $data = $request->validate(['doctor_id' => 'required|integer']);

        $record = $this->service->signMedicalRecord($id, (int) $data['doctor_id']);
        return ApiResponse::success($record, '病历签名成功');
    }

    /**
     * 查询患者病历
     */
    public function patientRecords(Request $request, int $patientId): JsonResponse
    {
        $user = $request->user();
        $records = $this->service->getPatientRecords($patientId, (int) $user->id);
        return ApiResponse::success($records);
    }
}
