import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../../../prisma/prisma.service';

interface CardLayoutField {
  fieldKey: string;
  source: 'system' | 'custom';
  width: 'full' | 'half';
}

interface CardLayoutBlock {
  blockKey: string;
  blockName: string;
  fields: CardLayoutField[];
}

interface SetLayoutDto {
  entityType: string;
  blocks: CardLayoutBlock[];
}

@Injectable()
export class CardLayoutService {
  constructor(private readonly prisma: PrismaService) {}

  /** Get effective layout: user override or admin default */
  async getEffectiveLayout(
    clubId: string | null,
    entityType: string,
    userId: string,
    forceDefault?: boolean,
  ): Promise<{ blocks: CardLayoutBlock[]; isDefault: boolean }> {
    if (!forceDefault) {
      // Check for user override
      const userLayout = await this.prisma.crmCardLayoutUser.findUnique({
        where: {
          userId_clubId_entityType: {
            userId,
            clubId: clubId ?? '',
            entityType,
          },
        },
      });

      if (userLayout && !userLayout.useDefault && userLayout.fields) {
        return {
          blocks: userLayout.fields as unknown as CardLayoutBlock[],
          isDefault: false,
        };
      }
    }

    // Fall back to admin default
    const adminLayout = await this.prisma.crmCardLayout.findUnique({
      where: {
        clubId_entityType: {
          clubId: clubId ?? '',
          entityType,
        },
      },
    });

    if (adminLayout) {
      return {
        blocks: adminLayout.fields as unknown as CardLayoutBlock[],
        isDefault: true,
      };
    }

    // No layout configured — return empty (frontend uses its own default)
    return { blocks: [], isDefault: true };
  }

  /** Set admin-default layout for entity type */
  async setAdminLayout(clubId: string | null, dto: SetLayoutDto) {
    return this.prisma.crmCardLayout.upsert({
      where: {
        clubId_entityType: {
          clubId: clubId ?? '',
          entityType: dto.entityType,
        },
      },
      create: {
        clubId: clubId || null,
        entityType: dto.entityType,
        fields: dto.blocks as any,
      },
      update: {
        fields: dto.blocks as any,
      },
    });
  }

  /** Set personal user layout override */
  async setUserLayout(userId: string, clubId: string | null, dto: SetLayoutDto) {
    return this.prisma.crmCardLayoutUser.upsert({
      where: {
        userId_clubId_entityType: {
          userId,
          clubId: clubId ?? '',
          entityType: dto.entityType,
        },
      },
      create: {
        userId,
        clubId: clubId || null,
        entityType: dto.entityType,
        useDefault: false,
        fields: dto.blocks as any,
      },
      update: {
        useDefault: false,
        fields: dto.blocks as any,
      },
    });
  }

  /** Reset user layout to admin default */
  async resetUserLayout(userId: string, clubId: string | null, entityType: string) {
    const existing = await this.prisma.crmCardLayoutUser.findUnique({
      where: {
        userId_clubId_entityType: {
          userId,
          clubId: clubId ?? '',
          entityType,
        },
      },
    });

    if (!existing) {
      throw new NotFoundException('User layout not found');
    }

    return this.prisma.crmCardLayoutUser.update({
      where: { id: existing.id },
      data: { useDefault: true, fields: Prisma.JsonNull },
    });
  }
}
