-- ============================================================================
-- UPPI MARKETPLACE - SEED INICIAL
-- Executar em db_erp
-- ============================================================================


-- ─── Roles ───
INSERT IGNORE INTO `roles` (`name`, `slug`, `is_system`) VALUES
('Administrador', 'admin', 1),
('Vendedor', 'seller', 1),
('Cliente', 'customer', 1),
('Operador CD', 'operator', 1),
('Motorista', 'driver', 1);

-- ─── Permissions basicas ───
INSERT IGNORE INTO `permissions` (`name`, `slug`, `module`) VALUES
('Visualizar Sellers', 'sellers-view', 'marketplace'),
('Gerenciar Sellers', 'sellers-manage', 'marketplace'),
('Visualizar Pedidos', 'orders-view', 'marketplace'),
('Gerenciar Pedidos', 'orders-manage', 'marketplace'),
('Visualizar Produtos', 'products-view', 'marketplace'),
('Moderar Produtos', 'products-moderate', 'marketplace'),
('Visualizar Financeiro', 'finance-view', 'finance'),
('Gerenciar Financeiro', 'finance-manage', 'finance'),
('Aprovar Repasses', 'settlements-approve', 'finance'),
('Executar Repasses', 'settlements-execute', 'finance'),
('Visualizar Estoque', 'stock-view', 'logistics'),
('Gerenciar Estoque', 'stock-manage', 'logistics'),
('Visualizar Rotas', 'routes-view', 'logistics'),
('Gerenciar Rotas', 'routes-manage', 'logistics'),
('Visualizar Fiscal', 'fiscal-view', 'fiscal'),
('Gerenciar Fiscal', 'fiscal-manage', 'fiscal'),
('Visualizar Config', 'config-view', 'config'),
('Gerenciar Config', 'config-manage', 'config'),
('Gerenciar Regras', 'rules-manage', 'config'),
('Visualizar Auditoria', 'audit-view', 'admin'),
('Gerenciar Usuarios', 'users-manage', 'admin');

-- ─── Role Permissions (admin tem tudo) ───
INSERT IGNORE INTO `role_permissions` (`role_id`, `permission_id`)
SELECT r.id, p.id FROM roles r, permissions p WHERE r.slug = 'admin';

-- ─── Admin padrao ───
INSERT IGNORE INTO `users` (`uuid`, `name`, `email`, `email_verified_at`, `password_hash`, `user_type`, `status`) VALUES
(UUID(), 'Admin UPPI', 'admin@uppi.app.br', NOW(), '$argon2id$v=19$m=65536,t=4,p=1$YTVhNTRjNTQ0ZjRmNGU$k8Gj5rQxZ3vN7wX2mP9bKcL4hF6dA1sE0iU8yT5oJ3w', 'admin', 'active');

-- ─── Associar admin ao role admin ───
INSERT IGNORE INTO `user_roles` (`user_id`, `role_id`, `granted_at`, `granted_by`)
SELECT u.id, r.id, NOW(), u.id
FROM users u, roles r
WHERE u.email = 'admin@uppi.app.br' AND r.slug = 'admin';

-- ─── Categorias raiz ───
INSERT IGNORE INTO `categories` (`name`, `slug`, `level`, `path`, `sort_order`, `is_active`) VALUES
('Eletronicos', 'eletronicos', 0, 'eletronicos', 1, 1),
('Moda', 'moda', 0, 'moda', 2, 1),
('Casa e Decoracao', 'casa-e-decoracao', 0, 'casa-e-decoracao', 3, 1),
('Esportes', 'esportes', 0, 'esportes', 4, 1),
('Beleza e Saude', 'beleza-e-saude', 0, 'beleza-e-saude', 5, 1),
('Brinquedos', 'brinquedos', 0, 'brinquedos', 6, 1),
('Automotivo', 'automotivo', 0, 'automotivo', 7, 1),
('Alimentos e Bebidas', 'alimentos-e-bebidas', 0, 'alimentos-e-bebidas', 8, 1),
('Pet Shop', 'pet-shop', 0, 'pet-shop', 9, 1),
('Livros', 'livros', 0, 'livros', 10, 1);

-- ─── Warehouse padrao ───
INSERT IGNORE INTO `warehouses` (`uuid`, `code`, `name`, `type`, `is_active`, `priority`) VALUES
(UUID(), 'CD-SP-01', 'CD Sao Paulo 01', 'owned', 1, 100);

-- ─── System Settings ───
INSERT IGNORE INTO `system_settings` (`group`, `key`, `value`, `value_type`) VALUES
('marketplace', 'commission_default', '0.10', 'decimal'),
('marketplace', 'marketplace_name', 'UPPI Marketplace', 'string'),
('payment', 'pix_timeout_minutes', '30', 'integer'),
('payment', 'boleto_timeout_hours', '72', 'integer'),
('payment', 'default_gateway', 'mercado_pago', 'string'),
('shipping', 'free_threshold', '199.90', 'decimal'),
('shipping', 'default_origin_zipcode', '01001000', 'string'),
('fiscal', 'environment', '2', 'integer'),
('fiscal', 'serie_nfe', '1', 'integer'),
('fiscal', 'serie_nfce', '1', 'integer'),
('general', 'currency', 'BRL', 'string'),
('general', 'timezone', 'America/Sao_Paulo', 'string'),
('general', 'items_per_page', '20', 'integer');

-- ─── Regras exemplo ───
INSERT IGNORE INTO `rules` (`domain`, `name`, `conditions`, `actions`, `priority`) VALUES
('free_shipping', 'Frete gratis acima de R$199',
 '[{"field":"order.total","operator":">=","value":199.90}]',
 '{"type":"free_shipping","params":{"apply_to":"cheapest"}}',
 10),
('free_shipping', 'Frete gratis SP capital',
 '[{"field":"order.total","operator":">=","value":99.90},{"field":"shipping.state","operator":"==","value":"SP"},{"field":"shipping.zipcode","operator":"between","value":["01000000","09999999"]}]',
 '{"type":"free_shipping","params":{"apply_to":"all"}}',
 20),
('warehouse_routing', 'SP/RJ/MG -> CD Sao Paulo',
 '[{"field":"shipping.state","operator":"in","value":["SP","RJ","MG"]}]',
 '{"type":"route_to_warehouse","params":{"warehouse_code":"CD-SP-01"}}',
 10),
('warehouse_routing', 'Nordeste -> CD Recife',
 '[{"field":"shipping.state","operator":"in","value":["PE","BA","CE","AL","SE","PB","RN","PI","MA"]}]',
 '{"type":"route_to_warehouse","params":{"warehouse_code":"CD-PE-01"}}',
 10),
('payment_gateway', 'PIX -> Mercado Pago',
 '[{"field":"payment.type","operator":"==","value":"pix"}]',
 '{"type":"use_gateway","params":{"gateway":"mercado_pago"}}',
 10),
('payment_gateway', 'Cartao Getnet preferencial',
 '[{"field":"payment.type","operator":"in","value":["credit_card","debit_card"]},{"field":"seller.gateway_preference","operator":"==","value":"getnet"}]',
 '{"type":"use_gateway","params":{"gateway":"getnet"}}',
 20),
('payment_gateway', 'Cartao fallback Mercado Pago',
 '[{"field":"payment.type","operator":"in","value":["credit_card","debit_card"]}]',
 '{"type":"use_gateway","params":{"gateway":"mercado_pago"}}',
 5),
('commission', 'Eletronicos 12%',
 '[{"field":"product.category_slug","operator":"starts_with","value":"eletronico"}]',
 '{"type":"set_commission","params":{"rate":0.12}}',
 10),
('commission', 'Moda 15%',
 '[{"field":"product.category_slug","operator":"starts_with","value":"moda"}]',
 '{"type":"set_commission","params":{"rate":0.15}}',
 10),
('auto_approve_return', 'Defeito < R$200 auto-aprovacao',
 '[{"field":"return.reason","operator":"==","value":"defective"},{"field":"return.refund_amount","operator":"<","value":200}]',
 '{"type":"auto_approve","params":{"generate_reverse_label":true}}',
 10),
('auto_approve_return', 'Seller premium auto-aprovacao',
 '[{"field":"seller.rating_avg","operator":">=","value":4.5},{"field":"return.refund_amount","operator":"<","value":500}]',
 '{"type":"auto_approve","params":{"generate_reverse_label":true}}',
 5),
('fraud_detection', 'Pedido alto de conta nova',
 '[{"field":"order.total","operator":">","value":2000},{"field":"user.account_age_days","operator":"<","value":7}]',
 '{"type":"flag_for_review","params":{"risk_level":"high","block_payment":false}}',
 20);

-- ─── Carriers padrao ───
INSERT IGNORE INTO `carriers` (`name`, `code`, `type`, `api_provider`, `is_active`) VALUES
('Correios SEDEX', 'correios-sedex', 'carrier', 'correios', 1),
('Correios PAC', 'correios-pac', 'carrier', 'correios', 1),
('Jadlog', 'jadlog', 'carrier', 'melhor_envio', 1),
('Frota Propria', 'frota-propria', 'own_fleet', NULL, 1);
