import { Knex } from 'knex';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import authConfig from '../../../config/auth';

/**
 * Seed database with initial data
 * Creates admin user, default API client, and example restaurants
 */
export async function seed(knex: Knex): Promise<void> {
  // Delete existing entries (in reverse order of dependencies)
  await knex('api_clients').del();
  await knex('user_restaurant_access').del();
  await knex('sales_data').del();
  await knex('pos_sync_logs').del();
  await knex('restaurant_outlets').del();
  await knex('restaurant_brands').del();
  await knex('restaurant_groups').del();
  await knex('password_reset_tokens').del();
  await knex('users').del();

  // Create admin user
  const adminPassword = process.env.ADMIN_PASSWORD || 'Admin123!';
  const hashedPassword = await bcrypt.hash(adminPassword, authConfig.password.saltRounds);

  const [adminUser] = await knex('users').insert({
    email: 'admin@example.com',
    password: hashedPassword,
    first_name: 'Admin',
    last_name: 'User',
    roles: JSON.stringify([authConfig.roles.admin]),
    permissions: JSON.stringify([
      authConfig.permissions.createRestaurant,
      authConfig.permissions.readRestaurant,
      authConfig.permissions.updateRestaurant,
      authConfig.permissions.deleteRestaurant,
      authConfig.permissions.createUser,
      authConfig.permissions.readUser,
      authConfig.permissions.updateUser,
      authConfig.permissions.deleteUser,
      authConfig.permissions.manageAccess,
      authConfig.permissions.syncData
    ])
  }).returning('id');

  // Create default API client for POS integration
  await knex('api_clients').insert({
    client_id: process.env.DEFAULT_CLIENT_ID || 'pos_client_' + crypto.randomBytes(8).toString('hex'),
    client_secret: process.env.DEFAULT_CLIENT_SECRET || crypto.randomBytes(32).toString('hex'),
    client_name: 'Default POS Client',
    client_description: 'Default API client for POS integration',
    allowed_scopes: JSON.stringify([
      authConfig.scopes.readRestaurant,
      authConfig.scopes.readSales,
      authConfig.scopes.writeSales,
      authConfig.scopes.syncData
    ]),
    active: true,
    created_at: new Date(),
    updated_at: new Date()
  });

  // Create a sample restaurant group
  const [restaurantGroup] = await knex('restaurant_groups').insert({
    name: 'Sample Restaurant Group',
    description: 'A sample restaurant group for demonstration',
    contact_email: 'contact@samplegroup.com',
    website: 'https://samplegroup.com'
  }).returning('id');

  // Create sample brands
  const [fastFoodBrand] = await knex('restaurant_brands').insert({
    group_id: restaurantGroup.id,
    name: 'Quick Bites',
    description: 'Fast food chain offering quick meals',
    theme_color: '#FF5733'
  }).returning('id');

  const [fineDiningBrand] = await knex('restaurant_brands').insert({
    group_id: restaurantGroup.id,
    name: 'Elegant Dining',
    description: 'Fine dining restaurants with exceptional cuisine',
    theme_color: '#3366FF'
  }).returning('id');

  // Create sample outlets
  await knex('restaurant_outlets').insert([
    {
      brand_id: fastFoodBrand.id,
      name: 'Quick Bites - Downtown',
      country: 'United States',
      address: '123 Main St, Downtown, City',
      contact_phone: '+1234567890',
      pos_id: 'QB-DT-001',
      currency: 'USD',
      active: true
    },
    {
      brand_id: fastFoodBrand.id,
      name: 'Quick Bites - Mall',
      country: 'United States',
      address: '456 Mall Ave, City',
      contact_phone: '+1234567891',
      pos_id: 'QB-ML-002',
      currency: 'USD',
      active: true
    },
    {
      brand_id: fineDiningBrand.id,
      name: 'Elegant Dining - Riverside',
      country: 'United States',
      address: '789 River Rd, Riverside, City',
      contact_phone: '+1234567892',
      pos_id: 'ED-RS-001',
      currency: 'USD',
      active: true
    }
  ]);

  // Give admin access to restaurant group
  await knex('user_restaurant_access').insert({
    user_id: adminUser.id,
    restaurant_id: restaurantGroup.id,
    restaurant_level: 'group',
    permissions: JSON.stringify([
      authConfig.permissions.readRestaurant,
      authConfig.permissions.updateRestaurant
    ])
  });

  console.log('Seed data inserted successfully');
}
