import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

const PERMISSION_MODULES = [
  'dashboard',
  'users',
  'houses',
  'shops',
  'products',
  'orders',
  'mcq',
  'menus',
  'teams',
  'settings',
  'community',
  'notifications',
] as const;

type Module = (typeof PERMISSION_MODULES)[number];

interface PermissionSet {
  module: Module;
  canView: boolean;
  canCreate: boolean;
  canEdit: boolean;
  canDelete: boolean;
}

function fullAccess(): PermissionSet[] {
  return PERMISSION_MODULES.map((module) => ({
    module,
    canView: true,
    canCreate: true,
    canEdit: true,
    canDelete: true,
  }));
}

function customAccess(
  modules: Module[],
  viewOnly: Module[] = []
): PermissionSet[] {
  return PERMISSION_MODULES.map((module) => {
    if (modules.includes(module)) {
      const isViewOnly = viewOnly.includes(module);
      return {
        module,
        canView: true,
        canCreate: !isViewOnly,
        canEdit: !isViewOnly,
        canDelete: !isViewOnly,
      };
    }
    return {
      module,
      canView: false,
      canCreate: false,
      canEdit: false,
      canDelete: false,
    };
  });
}

const defaultRoles = [
  {
    name: 'super_admin',
    label: 'Super Admin',
    description: 'Full access to all modules and settings',
    color: '#dc2626',
    isDefault: true,
    getPermissions: fullAccess,
  },
  {
    name: 'admin',
    label: 'Admin',
    description: 'Access to most modules except settings',
    color: '#ea580c',
    isDefault: true,
    getPermissions: () =>
      customAccess(
        [
          'dashboard',
          'users',
          'houses',
          'shops',
          'products',
          'orders',
          'mcq',
          'menus',
          'teams',
          'community',
          'notifications',
        ] as Module[]
      ),
  },
  {
    name: 'manager',
    label: 'Manager',
    description: 'View + Edit access to houses, shops, products, orders',
    color: '#16a34a',
    isDefault: true,
    getPermissions: () =>
      customAccess(
        ['dashboard', 'houses', 'shops', 'products', 'orders'] as Module[],
        ['dashboard'] as Module[]
      ),
  },
  {
    name: 'editor',
    label: 'Editor',
    description: 'View + Edit access to content (mcq, community, menus)',
    color: '#d97706',
    isDefault: true,
    getPermissions: () =>
      customAccess(
        ['dashboard', 'mcq', 'community', 'menus'] as Module[],
        ['dashboard'] as Module[]
      ),
  },
  {
    name: 'viewer',
    label: 'Viewer',
    description: 'View-only access to dashboard and listings',
    color: '#b45309',
    isDefault: true,
    getPermissions: () =>
      customAccess(
        ['dashboard', 'houses', 'shops', 'products', 'orders'] as Module[],
        ['dashboard', 'houses', 'shops', 'products', 'orders'] as Module[]
      ),
  },
];

export async function POST() {
  try {
    const results = [];

    for (const roleDef of defaultRoles) {
      const existing = await db.role.findUnique({
        where: { name: roleDef.name },
      });

      if (existing) {
        // Update existing default role
        await db.role.update({
          where: { name: roleDef.name },
          data: {
            label: roleDef.label,
            description: roleDef.description,
            color: roleDef.color,
            isDefault: true,
          },
        });

        // Replace permissions
        await db.rolePermission.deleteMany({
          where: { roleId: existing.id },
        });

        const permissions = roleDef.getPermissions();
        await db.rolePermission.createMany({
          data: permissions.map((p) => ({
            roleId: existing.id,
            module: p.module,
            canView: p.canView,
            canCreate: p.canCreate,
            canEdit: p.canEdit,
            canDelete: p.canDelete,
          })),
        });

        results.push({ name: roleDef.name, action: 'updated' });
      } else {
        // Create new role with permissions
        const permissions = roleDef.getPermissions();
        const role = await db.role.create({
          data: {
            name: roleDef.name,
            label: roleDef.label,
            description: roleDef.description,
            color: roleDef.color,
            isDefault: true,
            permissions: {
              create: permissions.map((p) => ({
                module: p.module,
                canView: p.canView,
                canCreate: p.canCreate,
                canEdit: p.canEdit,
                canDelete: p.canDelete,
              })),
            },
          },
        });

        results.push({ name: roleDef.name, action: 'created', id: role.id });
      }
    }

    return NextResponse.json({
      success: true,
      message: 'Default roles seeded successfully',
      results,
    });
  } catch (error) {
    console.error('Seed roles error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to seed roles' },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    const roles = await db.role.findMany({
      where: { isDefault: true },
      include: {
        permissions: { orderBy: { module: 'asc' } },
        _count: { select: { userRoles: true } },
      },
      orderBy: { createdAt: 'asc' },
    });

    return NextResponse.json({ success: true, roles });
  } catch (error) {
    console.error('Fetch default roles error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch default roles' },
      { status: 500 }
    );
  }
}
