<?php

declare(strict_types=1);

$root = getenv('POC_TARGET_ROOT');
$baseUrl = rtrim((string)getenv('POC_BASE_URL'), '/');
$dialect = getenv('POC_DIALECT');
if (!$root || !$baseUrl || !in_array($dialect, ['mysql', 'dm'], true)) exit(2);
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();

$host = getenv('POC_AI_HOST');
$port = getenv('POC_AI_PORT');
$schema = getenv('POC_AI_SCHEMA');
$dsn = $dialect === 'dm'
    ? "dm:host=$host;port=$port;schema=$schema"
    : "mysql:host=$host;port=$port;dbname=$schema;charset=utf8mb4";
$pdo = new PDO($dsn, getenv('POC_AI_USER'), getenv('POC_AI_PASSWORD'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$prefix = $dialect === 'dm' ? 'YOSHOP_' : 'yoshop_';
$userTable = $prefix . ($dialect === 'dm' ? 'USER' : 'user');
$statusTable = $prefix . ($dialect === 'dm' ? 'USER_WEIGHT_STATUS' : 'user_weight_status');
$scheduleTable = $prefix . ($dialect === 'dm' ? 'USER_COURSE_SCHEDULE' : 'user_course_schedule');
$pdo->query('SELECT COUNT(*) FROM ' . $statusTable . ' WHERE 1=0');
$pdo->query('SELECT COUNT(*) FROM ' . $scheduleTable . ' WHERE 1=0');
$marker = 'CDXCOURSE' . strtoupper(bin2hex(random_bytes(5)));
$token = 'CDXCOURSE-TOKEN-' . strtoupper(bin2hex(random_bytes(12)));
$userId = 0;
$statusId = 0;
$insert = $pdo->prepare('INSERT INTO ' . $userTable
    . ' (STORE_ID,MOBILE,NICK_NAME,BALANCE,GIFT_BALANCE,IS_DELETE,CREATE_TIME)'
    . ' VALUES (10001,?,?,?,?,0,?)');
$insert->execute(['', $marker, '0.00', '0.00', time()]);
$userId = (int)$pdo->lastInsertId();
if ($userId <= 0) throw new RuntimeException('Synthetic course user insert failed');
try {
    $start = strtotime(date('Y-m-d'));
    $end = strtotime('+7 days', $start);
    $createStatus = $pdo->prepare('INSERT INTO ' . $statusTable
        . ' (USER_ID,STORE_ID,START_DATE,END_DATE,INITIAL_WEIGHT,TARGET_WEIGHT,STATUS,DELETE_FLAG,CREATE_TIME,UPDATE_TIME)'
        . ' VALUES (?,10001,?, ?, ?, ?,1,0,?,?)');
    $createStatus->execute([$userId, $start, $end, '64', '64', time(), time()]);
    $statusId = (int)$pdo->lastInsertId();
    if ($statusId <= 0) throw new RuntimeException('Synthetic course weight status insert failed');
    \think\facade\Cache::set($token, [
        'user' => ['user_id' => $userId], 'password_version' => 0, 'login_type' => 'thirdparty',
    ], 300);
    $post = static function (string $path, array $form) use ($baseUrl, $token): array {
        $context = stream_context_create(['http' => [
            'method' => 'POST',
            'header' => 'Access-Token: ' . $token . "\r\nplatform: POC\r\n"
                . "Content-Type: application/x-www-form-urlencoded\r\n",
            'content' => http_build_query(['form' => $form]),
            'timeout' => 15, 'ignore_errors' => true,
        ]]);
        $body = file_get_contents($baseUrl . $path, false, $context);
        $result = is_string($body) ? json_decode($body, true) : null;
        if (!is_array($result)) throw new RuntimeException('Course schedule HTTP response not JSON');
        return $result;
    };
    $create = $post('/api/user.course_schedule/create?storeId=10001', [
        'weight_status_id' => $statusId,
        'start_date' => date('Y-m-d', $start), 'end_date' => date('Y-m-d', $end),
        'type' => 1,
    ]);
    if ((int)($create['status'] ?? 0) !== 200) {
        throw new RuntimeException('Course schedule create failed: '
            . mb_substr((string)($create['message'] ?? ''), 0, 100));
    }
    $scheduleId = (int)($create['data']['id'] ?? 0);
    if ($scheduleId <= 0) throw new RuntimeException('Course schedule ID missing');
    $read = $pdo->prepare('SELECT ID,USER_ID,WEIGHT_STATUS_ID,TYPE,IS_COMPLETE,START_DATE,END_DATE FROM '
        . $scheduleTable . ' WHERE ID=?');
    $read->execute([$scheduleId]);
    $row = array_change_key_case($read->fetch(PDO::FETCH_ASSOC) ?: [], CASE_LOWER);
    if ((int)($row['user_id'] ?? 0) !== $userId
        || (int)($row['weight_status_id'] ?? 0) !== $statusId
        || (int)($row['type'] ?? 0) !== 1
        || (int)($row['start_date'] ?? 0) !== $start) {
        throw new RuntimeException('Course schedule create database readback mismatch');
    }
    $update = $post('/api/user.course_schedule/update?storeId=10001', [
        'id' => $scheduleId, 'type' => 2, 'is_complete' => 1,
    ]);
    $read->execute([$scheduleId]);
    $updated = array_change_key_case($read->fetch(PDO::FETCH_ASSOC) ?: [], CASE_LOWER);
    if ((int)($update['status'] ?? 0) !== 200
        || (int)($updated['type'] ?? 0) !== 2
        || (int)($updated['is_complete'] ?? 0) !== 1) {
        throw new RuntimeException('Course schedule update database readback mismatch');
    }
    $invalid = $post('/api/user.course_schedule/update?storeId=10001', [
        'id' => $scheduleId, 'type' => 4,
    ]);
    if ((int)($invalid['status'] ?? 200) === 200) {
        throw new RuntimeException('Invalid course schedule type was accepted');
    }
    echo json_encode(['dialect' => $dialect, 'status' => 'passed',
        'course_schedule_create_update_invalid' => true,
        'schedule_rows' => 1, 'final_type' => 2]) . PHP_EOL;
} finally {
    \think\facade\Cache::delete($token);
    if ($userId > 0) {
        $pdo->prepare('DELETE FROM ' . $scheduleTable . ' WHERE USER_ID=? AND STORE_ID=10001')
            ->execute([$userId]);
        $pdo->prepare('DELETE FROM ' . $statusTable . ' WHERE USER_ID=? AND STORE_ID=10001')
            ->execute([$userId]);
        $pdo->prepare('DELETE FROM ' . $userTable . ' WHERE USER_ID=? AND NICK_NAME=?')
            ->execute([$userId, $marker]);
        foreach ([$scheduleTable, $statusTable, $userTable] as $table) {
            $check = $pdo->prepare('SELECT COUNT(*) FROM ' . $table . ' WHERE USER_ID=?');
            $check->execute([$userId]);
            if ((int)$check->fetchColumn() !== 0) {
                throw new RuntimeException('Synthetic course schedule cleanup left data');
            }
        }
    }
}
