-- 初始化 kintone_license_server 数据库

-- 创建数据库（需要管理员权限运行，或手动创建后运行此脚本）
-- CREATE DATABASE kintone_license_server;

-- 连接到数据库
-- \c kintone_license_server;

-- 创建 plugins 表：存储插件信息
CREATE TABLE IF NOT EXISTS plugins (
    id SERIAL PRIMARY KEY,
    plugin_id VARCHAR(255) UNIQUE NOT NULL,
    plugin_name VARCHAR(255) NOT NULL,
    private_key TEXT NOT NULL,
    deleted BOOLEAN DEFAULT FALSE
);

-- 创建 customers 表：客户信息
CREATE TABLE IF NOT EXISTS customers (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255),
    phone VARCHAR(50),
    comment TEXT
);

-- 创建 licenses 表：许可证记录
CREATE TABLE IF NOT EXISTS licenses (
    id SERIAL PRIMARY KEY,
    domain VARCHAR(255) NOT NULL,
    plugin_id VARCHAR(255) NOT NULL,
    expired_time TIMESTAMPTZ NOT NULL,
    purchase_date TIMESTAMPTZ,
    plugin_fk INTEGER REFERENCES plugins(id),
    customer_fk INTEGER REFERENCES customers(id),
    message TEXT,
    UNIQUE(domain, plugin_id) -- 确保每个 domain + plugin_id 组合唯一
);

-- 插入默认插件数据（使用现有的 RSA 私钥）
INSERT INTO plugins (plugin_id, plugin_name, private_key)
VALUES (
    'kintone-vue-template',
    'kintone Vue テンプレート',
    '-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDOAqDRabJn6vga
YXnWuYKPomQVNV0R0HPmuN1N4qo7OMDkFH2mln86w68/9/bHMb7TcVaFGxNblpe2
tIjr/u/XfnS2+NK6ckTWOhmPUrqLG6A3a4v49dymvFdfyjAYOCBTlKzrdQTjdFAX
5EUE007n/G+RxYiEAm0NXpVqa+aw/Yvm5+Lr7GrKpyamAAygu5jYDE3rateyfJ1h
P2fEXEqR4RPD5pgyKD+4ZVbygaYqAw4rZu4OOZ4QtPCtksSenn94Yx9UUlex3TNW
oTBrFp+8z9wjg+o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