modules/frontend/Write-Shared-Package.ps1

param(
    [string]$ProjectName,
    [string]$Platform,
    [string]$OutputPath,
    [string[]]$Entities,
    [string]$Language = "tr"
)

. (Join-Path (Split-Path $MyInvocation.MyCommand.Path) "..\core\Utils.ps1")
. (Join-Path (Split-Path $MyInvocation.MyCommand.Path) "..\core\Get-Locale.ps1")

$SharedRoot = switch ($Platform) {
    "Both"   { Join-Path $OutputPath "packages\shared" }
    "Mobile" { Join-Path $OutputPath "mobile\shared" }
    default  { Join-Path $OutputPath "frontend\src\shared" }
}

$SrcRoot = if ($Platform -eq "Both") { Join-Path $SharedRoot "src" } else { $SharedRoot }

# Klasörleri oluştur
if (-not $Global:DryRun) {
    New-Item -ItemType Directory -Path (Join-Path $SrcRoot "types") -Force | Out-Null
    New-Item -ItemType Directory -Path (Join-Path $SrcRoot "api") -Force | Out-Null
    New-Item -ItemType Directory -Path (Join-Path $SrcRoot "storage") -Force | Out-Null
    New-Item -ItemType Directory -Path (Join-Path $SrcRoot "i18n") -Force | Out-Null
}

# 1. package.json (Sadece Both modunda)
if ($Platform -eq "Both") {
    $pkg = @{
        name    = "shared"
        version = "0.1.0"
        private = $true
        main    = "./src/index.ts"
        types   = "./src/index.ts"
        dependencies = @{
            "i18next" = "^23.16.4"
        }
    }
    Write-CoreFile (Join-Path $SharedRoot "package.json") ($pkg | ConvertTo-Json -Depth 10)
}

# 2. types/index.ts
$typesContent = ""
foreach ($e in $Entities) {
    if ($e -eq "User") {
        $typesContent += "export interface User {`n id: number;`n username: string;`n role: string;`n isActive: boolean;`n createdAt: string;`n}`n`n"
    } else {
        $extra = if ($e -eq "Product") { "`n price: number;" } else { "" }
        $typesContent += "export interface $e {`n id: number;`n name: string;$extra`n createdAt: string;`n updatedAt: string;`n}`n`n"
    }
}
Write-CoreFile (Join-Path $SrcRoot "types\index.ts") $typesContent

# 3. api/apiClient.ts
$apiClientContent = @'
export class ApiClient {
  private baseUrl: string;
  private token: string | null = null;
 
  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }
 
  setToken(token: string | null) {
    this.token = token;
  }
 
  async request(path: string, options: RequestInit = {}) {
    const headers = new Headers(options.headers || {});
    if (this.token) {
      headers.set('Authorization', `Bearer ${this.token}`);
    }
    if (options.body && !headers.has('Content-Type')) {
      headers.set('Content-Type', 'application/json');
    }
 
    const response = await fetch(`${this.baseUrl}${path}`, {
      ...options,
      headers
    });
 
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(errorText || response.statusText);
    }
 
    if (response.status === 204) return null;
    return response.json();
  }
}
'@

Write-CoreFile (Join-Path $SrcRoot "api\apiClient.ts") $apiClientContent

# 4. storage/index.ts
$storageContent = @'
export interface IStorage {
  getItem(key: string): Promise<string | null>;
  setItem(key: string, value: string): Promise<void>;
  removeItem(key: string): Promise<void>;
}
 
export class WebStorage implements IStorage {
  async getItem(key: string): Promise<string | null> {
    return localStorage.getItem(key);
  }
  async setItem(key: string, value: string): Promise<void> {
    localStorage.setItem(key, value);
  }
  async removeItem(key: string): Promise<void> {
    localStorage.removeItem(key);
  }
}
'@

Write-CoreFile (Join-Path $SrcRoot "storage\index.ts") $storageContent

# 5. i18n/index.ts
$L_tr = Get-Locale -Language tr
$L_en = Get-Locale -Language en

$trDict = @{
    username      = $L_tr.uiUsername
    password      = $L_tr.uiPassword
    login         = $L_tr.uiLogin
    loginSubtitle = $L_tr.uiLoginSubtitle
    loginFailed   = $L_tr.uiLoginFailed
    logout        = $L_tr.uiLogout
    add           = $L_tr.uiAdd
    loading       = $L_tr.uiLoading
    noData        = $L_tr.uiNoData
    loadFailed    = $L_tr.uiLoadFailed
    addFailed     = $L_tr.uiAddFailed
    previous      = $L_tr.uiPrevious
    next          = $L_tr.uiNext
    page          = $L_tr.uiPage
    createdAt     = $L_tr.uiCreatedAt
    newEntity     = $L_tr.uiNewEntity
    entityList    = $L_tr.uiEntityList
    entityAdded   = $L_tr.uiEntityAdded
    entityName    = $L_tr.uiEntityName
    price         = $L_tr.uiPrice
    invalidCreds  = $L_tr.backendInvalidCreds
}

$enDict = @{
    username      = $L_en.uiUsername
    password      = $L_en.uiPassword
    login         = $L_en.uiLogin
    loginSubtitle = $L_en.uiLoginSubtitle
    loginFailed   = $L_en.uiLoginFailed
    logout        = $L_en.uiLogout
    add           = $L_en.uiAdd
    loading       = $L_en.uiLoading
    noData        = $L_en.uiNoData
    loadFailed    = $L_en.uiLoadFailed
    addFailed     = $L_en.uiAddFailed
    previous      = $L_en.uiPrevious
    next          = $L_en.uiNext
    page          = $L_en.uiPage
    createdAt     = $L_en.uiCreatedAt
    newEntity     = $L_en.uiNewEntity
    entityList    = $L_en.uiEntityList
    entityAdded   = $L_en.uiEntityAdded
    entityName    = $L_en.uiEntityName
    price         = $L_en.uiPrice
    invalidCreds  = $L_en.backendInvalidCreds
}

$trJson = $trDict | ConvertTo-Json -Depth 10
$enJson = $enDict | ConvertTo-Json -Depth 10

$i18nContent = @"
export const resources = {
  tr: {
    translation: $trJson
  },
  en: {
    translation: $enJson
  }
};
"@

Write-CoreFile (Join-Path $SrcRoot "i18n\index.ts") $i18nContent

# 6. index.ts (Root Export)
$indexContent = @'
export * from './types';
export * from './api/apiClient';
export * from './storage';
export * from './i18n';
'@

Write-CoreFile (Join-Path $SrcRoot "index.ts") $indexContent