import { randomUUID } from 'node:crypto';
import { normalizeUsername } from '../domain/normalization.js';
import { generateTemporaryPassword, hashPassword } from './passwords.js';
import { PERMISSIONS } from './rbac.js';
const permissionLabels = {
    [PERMISSIONS.USERS_MANAGE]: ['مدیریت کاربران', 'کاربران'],
    [PERMISSIONS.ROLES_MANAGE]: ['مدیریت نقش‌ها و مجوزها', 'کاربران'],
    [PERMISSIONS.SECURITY_AUDIT_VIEW]: ['مشاهده ممیزی امنیتی', 'ممیزی'],
    [PERMISSIONS.SETTINGS_MANAGE]: ['مدیریت تنظیمات سامانه', 'تنظیمات'],
    [PERMISSIONS.INVOICES_VIEW_ALL]: ['مشاهده همه فاکتورها', 'فاکتورها'],
    [PERMISSIONS.INVOICES_MANAGE]: ['ایجاد و ویرایش فاکتور', 'فاکتورها'],
    [PERMISSIONS.INVOICES_ARCHIVE]: ['بایگانی و بازیابی فاکتور', 'فاکتورها'],
    [PERMISSIONS.DELIVERIES_APPROVE]: ['تأیید درخواست تحویل', 'تحویل'],
    [PERMISSIONS.DELIVERIES_WAREHOUSE_VIEW]: ['مشاهده صف انبار مرتبط', 'تحویل'],
    [PERMISSIONS.DELIVERIES_WAREHOUSE_ACT]: ['ثبت عملیات انبار', 'تحویل'],
    [PERMISSIONS.DISCREPANCIES_RESOLVE]: ['رفع مغایرت‌ها', 'مغایرت'],
    [PERMISSIONS.PRODUCTS_MANAGE]: ['مدیریت کالاها', 'کالاها'],
    [PERMISSIONS.REQUESTERS_MANAGE]: ['مدیریت درخواست‌کنندگان', 'درخواست‌کنندگان'],
    [PERMISSIONS.IMPORTS_INVOICES]: ['ورود فایل فاکتورها', 'ورود اطلاعات'],
    [PERMISSIONS.IMPORTS_PRODUCTS]: ['ورود فهرست کالاها', 'ورود اطلاعات'],
    [PERMISSIONS.REPORTS_VIEW]: ['مشاهده و خروجی گزارش‌ها', 'گزارش‌ها'],
    [PERMISSIONS.AUDIT_VIEW_OPERATIONAL]: ['مشاهده تاریخچه عملیاتی', 'ممیزی']
};
const rolePermissions = {
    super_admin: Object.values(PERMISSIONS),
    supply_manager: [
        PERMISSIONS.INVOICES_VIEW_ALL,
        PERMISSIONS.INVOICES_MANAGE,
        PERMISSIONS.INVOICES_ARCHIVE,
        PERMISSIONS.DELIVERIES_APPROVE,
        PERMISSIONS.DISCREPANCIES_RESOLVE,
        PERMISSIONS.PRODUCTS_MANAGE,
        PERMISSIONS.REQUESTERS_MANAGE,
        PERMISSIONS.IMPORTS_INVOICES,
        PERMISSIONS.REPORTS_VIEW,
        PERMISSIONS.AUDIT_VIEW_OPERATIONAL
    ],
    warehouse_operator: [PERMISSIONS.DELIVERIES_WAREHOUSE_VIEW, PERMISSIONS.DELIVERIES_WAREHOUSE_ACT]
};
async function seedReferenceData(tx) {
    const branchId = randomUUID();
    await tx.query(`INSERT INTO branches(id, code, name) VALUES ($1, 'MAIN', 'شعبه مرکزی')
     ON CONFLICT(code) DO UPDATE SET name = EXCLUDED.name`, [branchId]);
    const branch = await tx.query('SELECT id FROM branches WHERE code = $1', ['MAIN']);
    const warehouseId = randomUUID();
    await tx.query(`INSERT INTO warehouses(id, branch_id, code, name) VALUES ($1, $2, 'MAIN-WH', 'انبار مرکزی')
     ON CONFLICT(code) DO UPDATE SET name = EXCLUDED.name`, [warehouseId, branch.rows[0].id]);
    const warehouse = await tx.query('SELECT id FROM warehouses WHERE code = $1', ['MAIN-WH']);
    for (const [code, [name, module]] of Object.entries(permissionLabels)) {
        await tx.query(`INSERT INTO permissions(id, code, name_fa, module) VALUES ($1,$2,$3,$4)
       ON CONFLICT(code) DO UPDATE SET name_fa = EXCLUDED.name_fa, module = EXCLUDED.module`, [randomUUID(), code, name, module]);
    }
    const roles = [
        ['super_admin', 'مدیریت کل'],
        ['supply_manager', 'مدیر تأمین'],
        ['warehouse_operator', 'انباردار']
    ];
    for (const [code, name] of roles) {
        await tx.query(`INSERT INTO roles(id, code, name_fa, is_system) VALUES ($1,$2,$3,true)
       ON CONFLICT(code) DO UPDATE SET name_fa = EXCLUDED.name_fa`, [randomUUID(), code, name]);
    }
    for (const [roleCode, codes] of Object.entries(rolePermissions)) {
        await tx.query(`INSERT INTO role_permissions(role_id, permission_id)
       SELECT r.id, p.id FROM roles r CROSS JOIN permissions p
       WHERE r.code = $1 AND p.code = ANY($2::text[])
       ON CONFLICT DO NOTHING`, [roleCode, codes]);
    }
    return { branchId: branch.rows[0].id, warehouseId: warehouse.rows[0].id };
}
export async function seedDatabase(database, demoUsers) {
    return database.transaction(async (tx) => {
        const refs = await seedReferenceData(tx);
        await tx.query(`INSERT INTO requesters(id, code, name, normalized_name)
       SELECT $1, 'REQ-001', 'فروش مرکزی', 'فروش مرکزی'
       WHERE NOT EXISTS (SELECT 1 FROM requesters WHERE code = 'REQ-001')`, [randomUUID()]);
        if (!demoUsers)
            return [];
        const definitions = [
            { username: 'admin', name: 'مدیر سامانه', role: 'super_admin' },
            { username: 'supply', name: 'مدیر تأمین نمونه', role: 'supply_manager' },
            { username: 'warehouse', name: 'انباردار نمونه', role: 'warehouse_operator' }
        ];
        const credentials = [];
        for (const definition of definitions) {
            const exists = await tx.query('SELECT id FROM users WHERE username_normalized = $1', [definition.username]);
            if (exists.rowCount)
                continue;
            const password = generateTemporaryPassword();
            const userId = randomUUID();
            await tx.query(`INSERT INTO users(id, branch_id, warehouse_id, name, username, username_normalized, password_hash)
         VALUES ($1,$2,$3,$4,$5,$6,$7)`, [
                userId,
                refs.branchId,
                definition.role === 'warehouse_operator' ? refs.warehouseId : null,
                definition.name,
                definition.username,
                normalizeUsername(definition.username),
                await hashPassword(password)
            ]);
            await tx.query(`INSERT INTO user_roles(user_id, role_id) SELECT $1, id FROM roles WHERE code = $2`, [userId, definition.role]);
            credentials.push({ username: definition.username, password, role: definition.role });
        }
        return credentials;
    });
}
//# sourceMappingURL=seed-data.js.map