import { describe, expect, it, vi } from 'vitest'

describe('listTemplates', () => {
  it('returns paginated items and preserves system-first ordering from the query result', async () => {
    const select = vi.fn(() => ({
      from: vi.fn(() => ({
        where: vi.fn(() => ({
          orderBy: vi.fn().mockResolvedValue([
            {
              id: 'system-1',
              tenantId: null,
              name: 'Brand Identity',
              description: null,
              category: 'design',
              estimatedDays: 30,
              billingType: 'fixed',
              thumbnailEmoji: '🎨',
              isPublic: true,
              usageCount: 10,
              createdBy: null,
              createdAt: new Date('2026-06-01T00:00:00.000Z'),
              updatedAt: new Date('2026-06-01T00:00:00.000Z'),
            },
            {
              id: 'tenant-1',
              tenantId: 'tenant-1',
              name: 'My Template',
              description: null,
              category: 'consulting',
              estimatedDays: 7,
              billingType: 'retainer',
              thumbnailEmoji: '📋',
              isPublic: false,
              usageCount: 2,
              createdBy: 'user-1',
              createdAt: new Date('2026-06-02T00:00:00.000Z'),
              updatedAt: new Date('2026-06-02T00:00:00.000Z'),
            },
          ]),
        })),
      })),
    }))
    const db = { select }

    const { listTemplates } = await import('../../src/queries/project-templates')
    const result = await listTemplates(db as never, 'tenant-1', { page: 1, pageSize: 1 })

    expect(result).toEqual({
      items: [
        expect.objectContaining({
          id: 'system-1',
          is_system: true,
          name: 'Brand Identity',
        }),
      ],
      total: 2,
      page: 1,
      pageSize: 1,
    })
  })
})

describe('resolveFirstMemberWithRole', () => {
  it('returns the first active member matching the requested role', async () => {
    const limit = vi.fn().mockResolvedValue([{ userId: 'user-2' }])
    const orderBy = vi.fn(() => ({ limit }))
    const where = vi.fn(() => ({ orderBy }))
    const innerJoinUsers = vi.fn(() => ({ where }))
    const innerJoinRoles = vi.fn(() => ({ innerJoin: innerJoinUsers }))
    const from = vi.fn(() => ({ innerJoin: innerJoinRoles }))
    const select = vi.fn(() => ({ from }))
    const db = { select }

    const { resolveFirstMemberWithRole } = await import('../../src/queries/project-templates')
    const result = await resolveFirstMemberWithRole(db as never, 'tenant-1', 'ADMIN')

    expect(result).toBe('user-2')
    expect(select).toHaveBeenCalledTimes(1)
    expect(limit).toHaveBeenCalledWith(1)
  })
})
