-- Ether PMS Database Initialization Script
-- Database: ether_pms
-- Version: 2.0

-- ============================================
-- Auth Module Tables
-- ============================================

-- User Table
CREATE TABLE IF NOT EXISTS auth_user (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    username VARCHAR(50) UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    salt VARCHAR(32),
    real_name VARCHAR(50),
    phone VARCHAR(20),
    email VARCHAR(100),
    avatar VARCHAR(200),
    status VARCHAR(20) DEFAULT 'ACTIVE',
    last_login_time TIMESTAMP,
    last_login_ip VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    created_by UUID
);

CREATE INDEX IF NOT EXISTS idx_auth_user_username ON auth_user(username);
CREATE INDEX IF NOT EXISTS idx_auth_user_phone ON auth_user(phone);
CREATE INDEX IF NOT EXISTS idx_auth_user_status ON auth_user(status);

-- Role Table
CREATE TABLE IF NOT EXISTS auth_role (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(50) NOT NULL,
    description VARCHAR(200),
    type VARCHAR(20),
    data_scope VARCHAR(20) DEFAULT 'SELF',
    project_id VARCHAR(50),
    status VARCHAR(20) DEFAULT 'ENABLED',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_auth_role_code ON auth_role(code);
CREATE INDEX IF NOT EXISTS idx_auth_role_project ON auth_role(project_id);

-- Permission Table
CREATE TABLE IF NOT EXISTS auth_permission (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(100) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    type VARCHAR(20),
    resource VARCHAR(50),
    method VARCHAR(50),
    description VARCHAR(200),
    parent_code VARCHAR(50),
    sort_order INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_auth_permission_code ON auth_permission(code);
CREATE INDEX IF NOT EXISTS idx_auth_permission_type ON auth_permission(type);
CREATE INDEX IF NOT EXISTS idx_auth_permission_parent ON auth_permission(parent_code);

-- User-Role Relation Table
CREATE TABLE IF NOT EXISTS auth_user_role (
    user_id UUID REFERENCES auth_user(id) ON DELETE CASCADE,
    role_id UUID REFERENCES auth_role(id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);

-- Role-Permission Relation Table
CREATE TABLE IF NOT EXISTS auth_role_permission (
    role_id UUID REFERENCES auth_role(id) ON DELETE CASCADE,
    permission_id UUID REFERENCES auth_permission(id) ON DELETE CASCADE,
    PRIMARY KEY (role_id, permission_id)
);

-- ============================================
-- MDM Module Tables
-- ============================================

-- Project Table
CREATE TABLE IF NOT EXISTS mdm_project (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    description VARCHAR(500),
    address VARCHAR(200),
    project_type VARCHAR(20),
    province VARCHAR(50),
    city VARCHAR(50),
    district VARCHAR(50),
    longitude DOUBLE PRECISION,
    latitude DOUBLE PRECISION,
    status VARCHAR(20) DEFAULT 'ACTIVE',
    building_count INTEGER,
    unit_count INTEGER,
    room_count INTEGER,
    floor_count INTEGER,
    logo VARCHAR(200),
    contact VARCHAR(200),
    contact_phone VARCHAR(20),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_mdm_project_code ON mdm_project(code);
CREATE INDEX IF NOT EXISTS idx_mdm_project_status ON mdm_project(status);

-- Space Node Table
CREATE TABLE IF NOT EXISTS mdm_space_node (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(50) NOT NULL,
    name VARCHAR(100) NOT NULL,
    node_type VARCHAR(50) NOT NULL,
    parent_code VARCHAR(50),
    project_code VARCHAR(50) NOT NULL,
    sort_order INTEGER DEFAULT 0,
    building VARCHAR(50),
    unit VARCHAR(50),
    floor VARCHAR(50),
    room_number VARCHAR(50),
    area INTEGER,
    status VARCHAR(20) DEFAULT 'ACTIVE',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(code, project_code)
);

CREATE INDEX IF NOT EXISTS idx_mdm_space_node_project ON mdm_space_node(project_code);
CREATE INDEX IF NOT EXISTS idx_mdm_space_node_type ON mdm_space_node(node_type);
CREATE INDEX IF NOT EXISTS idx_mdm_space_node_parent ON mdm_space_node(parent_code);

-- ============================================
-- Initial Data
-- ============================================

-- Insert default admin user
-- Password: Admin123! (BCrypt encrypted)
-- Password requirements: 8-20 chars, uppercase, lowercase, digit, special char
INSERT INTO auth_user (username, password, real_name, status)
VALUES ('admin', '$2a$10$N9qo8uLOickgx2ZMRZoMye/U.N4.5F.HQW5R.HGmh3R1VJfF5WQa', '系统管理员', 'ACTIVE')
ON CONFLICT (username) DO NOTHING;

-- Insert default roles
INSERT INTO auth_role (code, name, description, type, data_scope, status)
VALUES
    ('SYSTEM_ADMIN', '系统管理员', '系统超级管理员', 'SYSTEM', 'ALL', 'ENABLED'),
    ('PROJECT_ADMIN', '项目管理员', '项目管理员', 'PROJECT', 'PROJECT', 'ENABLED'),
    ('EMPLOYEE', '普通员工', '普通员工', 'DEPARTMENT', 'SELF', 'ENABLED')
ON CONFLICT (code) DO NOTHING;

-- Insert comprehensive permissions
-- Format: module:action (e.g., dashboard:view, system:menu)
INSERT INTO auth_permission (code, name, type, resource, method, description, sort_order)
VALUES
    -- Dashboard / 仪表盘
    ('dashboard:view', '查看仪表盘', 'MENU', '/dashboard', 'GET', '查看仪表盘', 1),

    -- System Management / 系统管理
    ('system:menu', '系统管理', 'MENU', '/system', 'GET', '系统管理菜单', 99),
    ('system:user:list', '用户列表', 'BUTTON', '/api/users', 'GET', '查看用户列表', 100),
    ('system:user:create', '创建用户', 'BUTTON', '/api/users', 'POST', '创建新用户', 101),
    ('system:user:update', '更新用户', 'BUTTON', '/api/users', 'PUT', '更新用户信息', 102),
    ('system:user:delete', '删除用户', 'BUTTON', '/api/users', 'DELETE', '删除用户', 103),
    ('system:user:resetPwd', '重置密码', 'BUTTON', '/api/users/*/reset-password', 'POST', '重置用户密码', 104),
    ('system:user:export', '导出用户', 'BUTTON', '/api/users/export', 'GET', '导出用户数据', 105),

    -- Role Management / 角色管理
    ('system:role:list', '角色列表', 'BUTTON', '/api/roles', 'GET', '查看角色列表', 200),
    ('system:role:create', '创建角色', 'BUTTON', '/api/roles', 'POST', '创建新角色', 201),
    ('system:role:update', '更新角色', 'BUTTON', '/api/roles', 'PUT', '更新角色信息', 202),
    ('system:role:delete', '删除角色', 'BUTTON', '/api/roles', 'DELETE', '删除角色', 203),
    ('system:role:assignPermissions', '分配权限', 'BUTTON', '/api/roles/*/permissions', 'POST', '为角色分配权限', 204),

    -- Permission Management / 权限管理
    ('system:permission:list', '权限列表', 'BUTTON', '/api/permissions', 'GET', '查看权限列表', 300),
    ('system:permission:create', '创建权限', 'BUTTON', '/api/permissions', 'POST', '创建新权限', 301),
    ('system:permission:update', '更新权限', 'BUTTON', '/api/permissions', 'PUT', '更新权限信息', 302),
    ('system:permission:delete', '删除权限', 'BUTTON', '/api/permissions', 'DELETE', '删除权限', 303),

    -- Project Management / 项目管理
    ('project:list', '项目列表', 'MENU', '/api/projects', 'GET', '查看项目列表', 400),
    ('project:create', '创建项目', 'BUTTON', '/api/projects', 'POST', '创建新项目', 401),
    ('project:update', '更新项目', 'BUTTON', '/api/projects', 'PUT', '更新项目信息', 402),
    ('project:delete', '删除项目', 'BUTTON', '/api/projects', 'DELETE', '删除项目', 403),
    ('project:detail', '项目详情', 'BUTTON', '/api/projects/*', 'GET', '查看项目详情', 404),

    -- Space Management / 空间管理
    ('space:list', '空间列表', 'MENU', '/api/spaces', 'GET', '查看空间列表', 500),
    ('space:create', '创建空间', 'BUTTON', '/api/spaces', 'POST', '创建新空间', 501),
    ('space:update', '更新空间', 'BUTTON', '/api/spaces', 'PUT', '更新空间信息', 502),
    ('space:delete', '删除空间', 'BUTTON', '/api/spaces', 'DELETE', '删除空间', 503),
    ('space:import', '导入空间', 'BUTTON', '/api/spaces/import', 'POST', '批量导入空间', 504),
    ('space:export', '导出空间', 'BUTTON', '/api/spaces/export', 'GET', '导出空间数据', 505),

    -- Asset Management / 资产管理
    ('asset:list', '资产列表', 'MENU', '/api/assets', 'GET', '查看资产列表', 600),
    ('asset:create', '创建资产', 'BUTTON', '/api/assets', 'POST', '创建新资产', 601),
    ('asset:update', '更新资产', 'BUTTON', '/api/assets', 'PUT', '更新资产信息', 602),
    ('asset:delete', '删除资产', 'BUTTON', '/api/assets', 'DELETE', '删除资产', 603),
    ('asset:transfer', '资产调拨', 'BUTTON', '/api/assets/transfer', 'POST', '资产调拨', 604),
    ('asset:maintain', '资产维护', 'BUTTON', '/api/assets/maintain', 'POST', '资产维护记录', 605),

    -- Audit / 审计管理
    ('audit:view', '查看审计日志', 'MENU', '/api/audit', 'GET', '查看审计日志', 700),
    ('audit:export', '导出审计日志', 'BUTTON', '/api/audit/export', 'GET', '导出审计日志', 701),

    -- Finance / 财务管理
    ('finance:list', '财务列表', 'MENU', '/api/finance', 'GET', '查看财务列表', 800),
    ('finance:create', '创建财务记录', 'BUTTON', '/api/finance', 'POST', '创建财务记录', 801),
    ('finance:update', '更新财务记录', 'BUTTON', '/api/finance', 'PUT', '更新财务记录', 802),
    ('finance:delete', '删除财务记录', 'BUTTON', '/api/finance', 'DELETE', '删除财务记录', 803),
    ('finance:report', '财务报表', 'BUTTON', '/api/finance/report', 'GET', '生成财务报表', 804)
ON CONFLICT (code) DO NOTHING;

-- Assign all permissions to SYSTEM_ADMIN role
INSERT INTO auth_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM auth_role r, auth_permission p
WHERE r.code = 'SYSTEM_ADMIN'
AND NOT EXISTS (
    SELECT 1 FROM auth_role_permission rp
    WHERE rp.role_id = r.id AND rp.permission_id = p.id
);
