import { TenantTag, CreateTenantTagDto, UpdateTenantTagDto } from '@/domain/entities/tenant-tag';

function getAuthHeaders(): HeadersInit {
  const token = localStorage.getItem('token');
  const tenantId = localStorage.getItem('tenantId');
  return {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
    ...(tenantId ? { 'X-Tenant-Id': tenantId } : {}),
  };
}

const BASE = '/api/proxy';

export async function listTenantTags(): Promise<TenantTag[]> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags`, { headers: getAuthHeaders() });
  if (!res.ok) throw new Error(`Failed to fetch tenant tags: ${res.status}`);
  return res.json();
}

export async function createTenantTag(dto: CreateTenantTagDto): Promise<TenantTag> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags`, {
    method: 'POST',
    headers: getAuthHeaders(),
    body: JSON.stringify(dto),
  });
  if (!res.ok) throw new Error(`Failed to create tenant tag: ${res.status}`);
  return res.json();
}

export async function updateTenantTag(id: string, dto: UpdateTenantTagDto): Promise<TenantTag> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags/${id}`, {
    method: 'PUT',
    headers: getAuthHeaders(),
    body: JSON.stringify(dto),
  });
  if (!res.ok) throw new Error(`Failed to update tenant tag: ${res.status}`);
  return res.json();
}

export async function deleteTenantTag(id: string): Promise<void> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags/${id}`, {
    method: 'DELETE',
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to delete tenant tag: ${res.status}`);
}

export async function getTagTenants(tagId: string): Promise<{ tenantId: string; tenantName: string }[]> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags/${tagId}/tenants`, { headers: getAuthHeaders() });
  if (!res.ok) throw new Error(`Failed to fetch tag tenants: ${res.status}`);
  return res.json();
}

export async function getTenantTags(tenantId: string): Promise<TenantTag[]> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags/tenants/${tenantId}`, { headers: getAuthHeaders() });
  if (!res.ok) throw new Error(`Failed to fetch tenant tags: ${res.status}`);
  return res.json();
}

export async function assignTagToTenants(tagId: string, tenantIds: string[]): Promise<void> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags/${tagId}/assign`, {
    method: 'POST',
    headers: getAuthHeaders(),
    body: JSON.stringify({ tenantIds }),
  });
  if (!res.ok) throw new Error(`Failed to assign tag: ${res.status}`);
}

export async function removeTagFromTenant(tagId: string, tenantId: string): Promise<void> {
  const res = await fetch(`${BASE}/api/v1/admin/tenant-tags/${tagId}/assign/${tenantId}`, {
    method: 'DELETE',
    headers: getAuthHeaders(),
  });
  if (!res.ok) throw new Error(`Failed to remove tag assignment: ${res.status}`);
}
