# All files / src/services config.ts

0% Statements 0/77
0% Branches 0/4
0% Functions 0/15
0% Lines 0/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398

     import { apiService } from './api';
    import { ApiResult } from '@/types';
    import { API_ENDPOINTS } from '@/constants/api';

    export interface SystemConfig {
      // Credit system configuration
      default_devices: number;
      credit_per_user_3_devices: number;
      credit_per_user_5_devices: number;
      credit_per_extra_device: number;

      // TMDB configuration
      tmdb_api_key?: string;
      tmdb_enabled: boolean;
      tmdb_language?: string;
      tmdb_mode?: 'online' | 'offline';
      tmdb_metadata_path?: string;
      tmdb_preferred_format?: 'original' | 'webp' | 'png' | 'jpg';

      // Content display options
      hide_empty_episodes?: boolean;

      // System information
      version: string;
      last_updated: string;
    }

    export interface CreditConfig {
      default_devices: number;
      credit_per_user_3_devices: number;
      credit_per_user_5_devices: number;
      credit_per_extra_device: number;
    }

    export interface TMDBConfig {
      tmdb_api_key?: string;
      tmdb_enabled: boolean;
      tmdb_language?: string;
      tmdb_mode: 'online' | 'offline';
      tmdb_metadata_path?: string;
      tmdb_preferred_format?: 'original' | 'webp' | 'png' | 'jpg';
    }

    export interface TMDBTestResult {
      valid: boolean;
      message: string;
      account_info?: {
        id: number;
        username: string;
        name: string;
      };
    }

    export interface SqliteImportSummary {
      tables: Array<{
        table: string;
        rows_seen: number;
        rows_inserted: number;
      }>;
      total_rows_seen: number;
      total_rows_inserted: number;
      errors?: Array<{
        table: string;
        error: string;
      }>;
    }

    export interface PostgresExportResult {
      file_name: string;
      download_url: string;
      size_bytes: number;
    }

    export interface PostgresImportResult {
      status: string;
    }

    export interface ImportTaskStartResponse {
      task_id: string;
      status: string;
      message: string;
    }

    export interface ImportTask {
      id: string;
      status: 'running' | 'completed' | 'failed' | 'cancelled';
      kind: 'sqlite' | 'postgres';
      mode?: string | null;
      source: string;
      start_time: number;
      end_time?: number | null;
      stage?: string | null;
      current_table?: string | null;
      current_table_index: number;
      total_tables: number;
      rows_seen: number;
      rows_inserted: number;
      error_message?: string | null;
      summary?: SqliteImportSummary | null;
    }

    // Stripe credits pricing config
    export interface PricingTier {
      min_qty: number;   // inclusive threshold
      percent: number;   // discount percent (0..=100)
    }

    export interface CreditsPricingConfig {
      base_price_usd: number;
      tiers: PricingTier[];
    }

    class ConfigService {
      // Get system configuration
      async getSystemConfig(): Promise<ApiResult<SystemConfig>> {
        try {
          const result = await apiService.get<SystemConfig>(API_ENDPOINTS.ADMIN.CONFIG);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Config Fetch Failed',
              details: 'Failed to fetch system configuration',
              timestamp: new Date().toISOString()}
          };
        }
      }

      // Update credit configuration
      async updateCreditConfig(config: CreditConfig): Promise<ApiResult<SystemConfig>> {
        try {
          const result = await apiService.put<SystemConfig>('/api/admin/config/credits', config);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Credit Config Update Failed',
              details: 'Failed to update credit configuration',
              timestamp: new Date().toISOString()}
          };
        }
      }

      // Update TMDB configuration
      // NOTE: Backend expects tmdb_mode values 'tmdb' | 'local'. Frontend uses 'online' | 'offline'.
      // Map frontend values to backend before sending.
      async updateTMDBConfig(config: TMDBConfig): Promise<ApiResult<SystemConfig>> {
        try {
          const payload: any = { ...config };
          if (payload.tmdb_mode === 'online') {
            payload.tmdb_mode = 'tmdb';
          } else if (payload.tmdb_mode === 'offline') {
            payload.tmdb_mode = 'local';
          }
          const result = await apiService.put<SystemConfig>('/api/admin/config/tmdb', payload);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'TMDB Config Update Failed',
              details: 'Failed to update TMDB configuration',
              timestamp: new Date().toISOString()}
          };
        }
      }

      // Test TMDB API key
      async testTMDBKey(apiKey: string): Promise<ApiResult<TMDBTestResult>> {
        try {
          const result = await apiService.post<TMDBTestResult>('/api/admin/config/tmdb/test', { tmdb_api_key: apiKey });
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'TMDB Test Failed',
              details: 'Failed to test TMDB API key',
              timestamp: new Date().toISOString()}
          };
        }
      }

      // Get system statistics
      async getSystemStats(): Promise<ApiResult<{
        total_users: number;
        total_resellers: number;
        total_content: number;
        total_active_devices: number;
        total_credits_used: number;
        system_uptime: string;
      }>> {
        try {
          const result = await apiService.get<{
            total_users: number;
            total_resellers: number;
            total_content: number;
            total_active_devices: number;
            total_credits_used: number;
            system_uptime: string;
          }>(API_ENDPOINTS.ADMIN.STATS);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Stats Fetch Failed',
              details: 'Failed to fetch system statistics',
              timestamp: new Date().toISOString()}
          };
        }
      }

      // Admin: get credits purchase pricing config
      async getCreditsPricing(): Promise<ApiResult<CreditsPricingConfig>> {
        try {
          const result = await apiService.get<CreditsPricingConfig>(API_ENDPOINTS.ADMIN.CREDITS_PRICING_CONFIG);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Pricing Config Fetch Failed',
              details: 'Failed to fetch credits pricing configuration',
              timestamp: new Date().toISOString()}
          };
        }
      }

      // Admin: update credits purchase pricing config
      async updateCreditsPricing(config: CreditsPricingConfig): Promise<ApiResult<CreditsPricingConfig>> {
        try {
          const result = await apiService.put<CreditsPricingConfig>(API_ENDPOINTS.ADMIN.CREDITS_PRICING_CONFIG, config);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Pricing Config Update Failed',
              details: 'Failed to update credits pricing configuration',
              timestamp: new Date().toISOString()}
          };
        }
      }
      async updateConfig(key: string, value: string): Promise<ApiResult<{ message: string; key: string; value: string }>> {
        try {
          const result = await apiService.put<{ message: string; key: string; value: string }>(API_ENDPOINTS.ADMIN.CONFIG, {
            key,
            value});
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Config Update Failed',
              details: `Failed to update config ${key}`,
              timestamp: new Date().toISOString()}
          };
        }
      }

      async importLegacySqlite(file: File): Promise<ApiResult<{ summary: SqliteImportSummary }>> {
        try {
          const form = new FormData();
          form.append('db', file);
          const result = await apiService.post<{ summary: SqliteImportSummary }>(
            API_ENDPOINTS.ADMIN.SQLITE_IMPORT_UPLOAD,
            form
          );
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'SQLite Import Failed',
              details: 'Failed to import legacy SQLite database',
              timestamp: new Date().toISOString()}
          };
        }
      }

      async startLegacySqliteImport(file: File): Promise<ApiResult<ImportTaskStartResponse>> {
        try {
          const form = new FormData();
          form.append('db', file);
          const result = await apiService.post<ImportTaskStartResponse>(
            `${API_ENDPOINTS.ADMIN.SQLITE_IMPORT_UPLOAD}?async=true`,
            form
          );
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'SQLite Import Failed',
              details: 'Failed to start legacy SQLite import',
              timestamp: new Date().toISOString()}
          };
        }
      }

      async exportPostgresBackup(): Promise<ApiResult<PostgresExportResult>> {
        try {
          // Pass empty body to ensure Content-Type: application/json is sent
          const result = await apiService.post<PostgresExportResult>(API_ENDPOINTS.ADMIN.DB.EXPORT, {});
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Export Failed',
              details: 'Failed to create PostgreSQL backup',
              timestamp: new Date().toISOString()}
          };
        }
      }

      async importPostgresBackup(file: File, mode: 'append' | 'replace'): Promise<ApiResult<PostgresImportResult>> {
        try {
          const form = new FormData();
          form.append('sql', file);
          const result = await apiService.post<PostgresImportResult>(
            `${API_ENDPOINTS.ADMIN.DB.IMPORT}?mode=${encodeURIComponent(mode)}`,
            form,
            {
              headers: {
                'Content-Type': 'multipart/form-data'}}
          );
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Import Failed',
              details: 'Failed to import PostgreSQL backup',
              timestamp: new Date().toISOString()}
          };
        }
      }

      async startPostgresImport(file: File, mode: 'append' | 'replace'): Promise<ApiResult<ImportTaskStartResponse>> {
        try {
          const form = new FormData();
          form.append('sql', file);
          const result = await apiService.post<ImportTaskStartResponse>(
            `${API_ENDPOINTS.ADMIN.DB.IMPORT}?mode=${encodeURIComponent(mode)}&async=true`,
            form,
            {
              headers: {
                'Content-Type': 'multipart/form-data'}}
          );
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Import Failed',
              details: 'Failed to start PostgreSQL import',
              timestamp: new Date().toISOString()}
          };
        }
      }

      async getImportTasks(): Promise<ApiResult<ImportTask[]>> {
        try {
          const result = await apiService.get<ImportTask[]>(API_ENDPOINTS.ADMIN.IMPORT_TASKS);
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Import Tasks Failed',
              details: 'Failed to fetch import tasks',
              timestamp: new Date().toISOString()}
          };
        }
      }

      async getImportTask(taskId: string): Promise<ApiResult<ImportTask>> {
        try {
          const result = await apiService.get<ImportTask>(API_ENDPOINTS.ADMIN.IMPORT_TASK(taskId));
          return result;
        } catch {
          return {
            success: false,
            error: {
              error: 'Import Task Failed',
              details: 'Failed to fetch import task',
              timestamp: new Date().toISOString()}
          };
        }
      }
    }

    export const configService = new ConfigService();